Passing data from middleware to API route #34263
Replies: 4 comments 1 reply
-
was a solution to this found? |
Beta Was this translation helpful? Give feedback.
-
Also liked a similar concept in SvelteKit Would be actually incredible to be able to define this e.g. in middleware and access in route handlers and server components. To me this makes nice dependency injection instead of heaving to rely on a sthg like a singleton for database or other connections and explaining typescript that it's not undefined as it was connected somewhere else, you just "pass it down" Or is there other patterns for this I'm missing? |
Beta Was this translation helpful? Give feedback.
-
An ugly workaround is to set cookies on the cloned request and to then access them using Middleware: const clonedRequest = request.clone();
clonedRequest.headers.append('Cookie', `locale=${locale}`);
// set cookies on cloned request so they are available with cookies() on first load
const response = NextResponse.rewrite(url.toString(), { request: clonedRequest });
return response; Layout/Page: export default function Page() {
const locale = cookies().get('locale')?.value;
} We do this in production, no issues so far, but a better technique would be welcome. |
Beta Was this translation helpful? Give feedback.
-
Hello,
I'd like to pass data from middleware to API route (eg. authenticated user) like this:
and access it in my API route like this:
Is that possible in Next.js? If not, at least a "hack" way?
Beta Was this translation helpful? Give feedback.
All reactions