How to pass a value from Next.js middleware to API routes and getServerSideProps
- Category
- Engineering
- Published
Compute a value in middleware and pass it to your API route or getServerSideProps. Works in both Node and Edge runtimes.
Unlike many web frameworks, Next.js middleware doesn't have a built-in mechanism for passing values from middleware to other parts of the application.
Instead, middleware has a feature called "rewrites" that we can leverage to pass data.
The high-level idea is to "rewrite" requests to the same URL, but modify the request's metadata to include the data we want to pass. Then, we can read the metadata from our API route or getServerSideProps.
Unfortunately, there are inconsistencies across runtimes that make it difficult to get this working. We hope these snippets help save you save you some headaches.
License: MIT
Usage: middleware.js
Usage: API route (Node)
Usage API route (Edge)
Usage: getServerSideProps (Edge and Node)
Source: (saved to context.js on your root)
Known limitations:
Depending on the runtime, your data will be transmitted as either an HTTP header or a URL query string. This leads to several limitations:
- Headers and query strings only accept strings for key/value pairs. If you'd like to use non-strings, you'll need to bring your own serializer
- Keys are lowercases because headers are case-insensitive
- Your host likely limits the total overall length of headers and query strings. Here are the limits for Vercel's edge runtime, for example
Ready to get started?
Sign up today