การสร้างบริบท tRPC
ทำความเข้าใจวิธีสร้างและเติมข้อมูลในออบเจ็กต์บริบทของ tRPC ด้วยข้อมูลเฉพาะคำขอ เช่น ข้อมูลผู้ใช้
การสร้างบริบท tRPC เป็นบทเรียน tRPC End-to-End Type Safe APIs ฟรีบน CoddyKit นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน tRPC End-to-End Type Safe APIs และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส tRPC End-to-End Type Safe APIs มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
What is tRPC Context?
Welcome! In tRPC, the context is a special object that's created for each incoming request to your server.
Think of it as a personalized backpack for every request. You can fill this backpack with any data that needs to be accessible by your tRPC procedures.
Why Use tRPC Context?
The tRPC context is incredibly useful for sharing request-specific data across all your API procedures. This prevents you from passing the same arguments repeatedly.
- Authentication: Store authenticated user details.
- Database Connections: Provide a database client for the current request.
- Request-specific Data: Access headers, IP addresses, or other request info.
- Logging: Attach a unique request ID for tracing.
Defining createContext
You define the context using a function, often named createContext. This function runs once for every incoming tRPC request.
It receives an object containing details about the incoming HTTP request (like headers) and should return the context object.
import { initTRPC } from '@trpc/server';
// This function runs on every request
function createContext(req: { headers: Record<string, string> }) {
console.log('Context created for a new request!');
return {
// We'll add more here later!
};
}
// We'll use this context to initialize tRPC
const t = initTRPC.context<ReturnType<typeof createContext>>().create();
console.log('tRPC initialized with context.');Accessing Request Details
Inside your createContext function, you get access to the underlying HTTP request object. This allows you to extract information like request headers or query parameters.
Let's grab a custom header, for example.
import { initTRPC } from '@trpc/server';
function createContext(req: { headers: Record<string, string> }) {
const userAgent = req.headers['user-agent'] || 'unknown';
return {
userAgent: userAgent
};
}
type Context = ReturnType<typeof createContext>;
const t = initTRPC.context<Context>().create();
// Simulate a request
const mockRequest = {
headers: { 'user-agent': 'CoddyKit-Browser' }
};
const ctx = createContext(mockRequest);
console.log('User Agent in context:', ctx.userAgent);Populating Context with Custom Data
You can populate the context object with any data derived from the request. A common use case is adding a user's ID or a full user object after an authentication check.
For now, let's just add a dummy user ID based on a header.
import { initTRPC } from '@trpc/server';
function createContext(req: { headers: Record<string, string> }) {
// In a real app, this would come from a JWT or session
const userId = req.headers['x-user-id'] || 'guest_user';
return {
userId: userId,
timestamp: new Date().toISOString()
};
}
type Context = ReturnType<typeof createContext>;
const t = initTRPC.context<Context>().create();
// Simulate a request with a custom user ID header
const mockRequest = {
headers: { 'x-user-id': 'coddykit_student_123' }
};
const ctx = createContext(mockRequest);
console.log('Context for request:', ctx);Typing Your Context
TypeScript is tRPC's superpower! It's crucial to properly type your context object so tRPC can provide full end-to-end type safety.
You can infer the type of your context directly from your createContext function using ReturnType.
import { initTRPC } from '@trpc/server';
function createContext(req: { headers: Record<string, string> }) {
const userId = req.headers['x-user-id'] || 'anonymous';
return {
userId: userId
};
}
// Infer the Context type from createContext function
type Context = ReturnType<typeof createContext>;
// Now, when initializing tRPC, provide this type
const t = initTRPC.context<Context>().create();
console.log('Context type inferred and used!');
// Example of how TypeScript would see the context:
// const typedContext: Context = { userId: 'some_id' };Using Context in Procedures
Once your context is defined and typed, any tRPC procedure can easily access it. Procedures receive an object with a ctx property, which holds your context object.
This makes user data, database clients, and other request-scoped data readily available.
import { initTRPC } from '@trpc/server';
function createContext(req: { headers: Record<string, string> }) {
const userId = req.headers['x-user-id'] || 'guest';
return { userId };
}
type Context = ReturnType<typeof createContext>;
const t = initTRPC.context<Context>().create();
const appRouter = t.router({
whoAmI: t.procedure.query(({ ctx }) => {
// Access userId directly from ctx
return `Hello, ${ctx.userId}!`;
}),
});
console.log('Procedure defined using context.');Context in Action: Full Example
Here's a simplified full example showing how createContext is defined and how its data is used within a tRPC procedure.
The output simulates what the procedure would return if called with the mock request.
import { initTRPC } from '@trpc/server';
// 1. Define your context function
function createContext(req: { headers: Record<string, string> }) {
const userId = req.headers['x-user-id'] || 'anonymous_user';
return {
userId: userId,
requestTime: new Date().toLocaleTimeString()
};
}
// 2. Infer the context type for type safety
type Context = ReturnType<typeof createContext>;
// 3. Initialize tRPC with the context type
const t = initTRPC.context<Context>().create();
// 4. Define a simple procedure that uses context
const appRouter = t.router({
getUserGreeting: t.procedure.query(({ ctx }) => {
return `Welcome back, ${ctx.userId}! Last accessed at: ${ctx.requestTime}.`;
}),
});
// --- Simulate a request and context creation ---
const mockRequest = {
headers: { 'x-user-id': 'CoddyKitUser' }
};
const contextForRequest = createContext(mockRequest);
console.log('Context created:', contextForRequest);
// Simulate the procedure call with the created context
const simulatedOutput = appRouter._def.procedures.getUserGreeting._def.query({ ctx: contextForRequest, input: undefined });
console.log('\nSimulated Procedure Output:');
console.log(simulatedOutput);Context Best Practices
To keep your tRPC application performant and maintainable:
- Keep it Lean: Only add data that's truly needed across multiple procedures.
- Avoid Heavy Logic: Complex operations (like database queries for user data) might be better placed in middleware or services called from context.
- Security: Always validate and sanitize any data extracted from the raw request before adding it to context.
Context Understanding Check
Let's check your understanding of tRPC context.
Recap: tRPC Context
You've learned about the powerful tRPC context!
- It's an object created per-request.
- It allows sharing data like user info or database clients across all procedures.
- You define it with a
createContextfunction. - Type safety is ensured by inferring its type and using it during tRPC initialization.
- Procedures access context via the
ctxparameter.
Next, you'll see how to use context to implement authentication with middleware!
คำถามที่พบบ่อย
บทเรียน “การสร้างบริบท tRPC” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “การสร้างบริบท tRPC” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส tRPC End-to-End Type Safe APIs ให้อัปเกรดเป็น CoddyKit PRO คอร์ส tRPC End-to-End Type Safe APIs มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “การสร้างบริบท tRPC”
ทำความเข้าใจวิธีสร้างและเติมข้อมูลในออบเจ็กต์บริบทของ tRPC ด้วยข้อมูลเฉพาะคำขอ เช่น ข้อมูลผู้ใช้ คุณปฏิบัติ tRPC End-to-End Type Safe APIs ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน tRPC End-to-End Type Safe APIs หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน tRPC End-to-End Type Safe APIs บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน
บทเรียน “การสร้างบริบท tRPC” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน tRPC End-to-End Type Safe APIs นี้ได้ไหม
ได้ บทเรียน tRPC End-to-End Type Safe APIs ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- การสร้างบริบท tRPC
- มิดเดิลแวร์การตรวจสอบสิทธิ์
- สายโซ่มิดเดิลแวร์แบบกำหนดเอง
- มิดเดิลแวร์สำหรับบันทึกและจับเวลาประสิทธิภาพ