#Authorizing access to threads using onBeforeRequest

1 messages · Page 1 of 1 (latest)

hallow quarry
#

Hey team, looking for guidance around authorizing a request based on the thread id.

Looking to do something like this:

middleware: {
  onBeforeRequest: ({ request, threadId }) => {
    const token = getTokenFromRequest(request);
    const user = getUserIdFromToken(token);

    if (!canAccessThread(user, threadId)) {
      throw new AuthorizationError('')
    }
  }  
},

However it doesn't seem the request itself is passed to this middleware. Is there another recommendation you can give for how to handle this sort of authorization?

gloomy carbon
#

@hallow quarry
You can’t rely on request inside onBeforeRequest to validate users—CopilotKit doesn’t expose raw HTTP there. Instead, do auth checks early in your API handler (e.g., Next.js/Express/FastAPI) or GraphQL resolver, validate the user, and block unauthorized access. Then pass user info into CopilotKit’s ctx.properties. Inside onBeforeRequest, use those properties (like userId) along with the threadId to run any final checks
if (!canAccessThread(properties.userId, threadId)) throw new Error("Forbidden");

hallow quarry
#

This is very helpful, thank you! The only thing that makes me hesitate is that onBeforeRequest doesn't seem to get called for the initial loadAgentState call. Is there somewhere I can see exactly which requests will result in the middleware being triggered?