Next.js Discord

Discord Forum

Add some data to context nextjs middleware

Unanswered
Siamese Crocodile posted this in #help-forum
Open in Discord
Siamese CrocodileOP
Hi, I've just read astro docs and they have a really cool pattern where you can add some data to global context inside middleware and then read this data inside server components. Is there a way to do something like this in nextjs?

export function onRequest (context, next) {
    // intercept data from a request
    // optionally, modify the properties in `locals`
    context.locals.title = "New title";

    // return a Response or the result of calling `next()`
    return next();
};


---
const data = Astro.locals;
---
<h1>{data.title}</h1>
<p>This {data.property} is from middleware.</p>

11 Replies

here's an example

middleware.ts
export default async function middleware(req: NextRequest): Promise<NextResponse> {
  const newHeaders = new Headers(req.headers)
  newHeaders.set('X-My-Custom-Data', 'Hello world!')

  return NextResponse.next({
    request: {
      // New request headers
      headers: newHeaders,
    },
  });
}


page.tsx
export default function Page() {
  const data = headers().get("X-My-Custom-Data")!;
  return <p>{data}</p>;
}
Siamese CrocodileOP
Sure thanks
though be advised that this is only limited to strings :)
a JSON.stringify() or using superjson as a workaround should work just fine
Siamese CrocodileOP
Yeah ik
I wonder how astro does it under the hood
Because you can pass all there
perhaps the middleware and the pages are colocated within the same process?
this is mostly my guess, but next's middleware seem to be split from the actual code that renders the page
the fact that it doesn't support node apis, it's probably intended to be used on serverless environments