M
Mastra•3w ago
Yash

How to set runtimeContext with chatRoutes

In my current setup, i add some runtime context in the api/route.ts which is then passed to the agent.stream options. How do I implement the same when using chatRoute?
4 Replies
Mastra Triager
Mastra Triager•3w ago
šŸ“ Created GitHub issue: https://github.com/mastra-ai/mastra/issues/10385 šŸ” If you're experiencing an error, please provide a minimal reproducible example whenever possible to help us resolve it quickly. šŸ™ Thank you for helping us improve Mastra!
Grayson
Grayson•3w ago
Option 1: Middleware
export const mastra = new Mastra({
server: {
middleware: [
async (c, next) => {
const requestContext = c.get("requestContext");
requestContext.set("userId", c.req.header("x-user-id"));
await next();
},
],
},
});

chatRoute({ path: '/chat/:agentId' });
export const mastra = new Mastra({
server: {
middleware: [
async (c, next) => {
const requestContext = c.get("requestContext");
requestContext.set("userId", c.req.header("x-user-id"));
await next();
},
],
},
});

chatRoute({ path: '/chat/:agentId' });
Option 2: Send in Request Body
fetch('/api/chat/myAgent', {
method: 'POST',
body: JSON.stringify({
messages: [...],
requestContext: { userId: '123', tier: 'pro' }
})
});
fetch('/api/chat/myAgent', {
method: 'POST',
body: JSON.stringify({
messages: [...],
requestContext: { userId: '123', tier: 'pro' }
})
});
chatRoute automatically picks up requestContext from either source and passes it to agent.stream().
Yash
YashOP•7d ago
Hey! @Grayson Thanks for replying. can you point me to some documentation for the second option ? hey @Grayson ! can you help me in figuring out how to use the second option you suggested ? I have a bunch of api routes which stream different agents. I add runtime context at the Next.js api route level. This context comes from the frontend client as request body.
Grayson
Grayson•7d ago
Hey sorry, was out of office. Can you post a minimal repro of what you are trying to do? (I think I may have mixed up requestContext and runtimeContext in your question)

Did you find this page helpful?