Oct 05, 2022
Oct 05, 2022
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.
Usage: API route (Node)
Usage API route (Edge)
Usage: getServerSideProps (Edge and Node)
Source: (saved to context.js on your root)
Depending on the runtime, your data will be transmitted as either an HTTP header or a URL query string. This leads to several limitations:
Start completely free for up to 5,000 monthly active users and up to 10 monthly active orgs. No credit card required.
Learn more about our transparent per-user costs to estimate how much your company could save by implementing Clerk.
The latest news and updates from Clerk, sent to your inbox.