Back

Engineering


Oct 05, 2022

Back

Engineering


Oct 05, 2022

How to pass a value from Next.js middleware to API routes and getServerSideProps

Colin Sidoti

Colin Sidoti


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


Suggested reading

Introducing Web3 Authentication

Engineering

Introducing Web3 Authentication

Clerk is saving Web3 developers from the greatest evils of the Web2 platform: cookies, multifactor authentication, and profile enrichment

Colin Sidoti

Colin Sidoti


Jan 21, 2022

Clerk's logo

Start Now,
No Strings Attached

Start completely free for up to 5,000 monthly active users and up to 10 monthly active orgs. No credit card required.

Start building

Pricing built for

businesses of all sizes.

Learn more about our transparent per-user costs to estimate how much your company could save by implementing Clerk.

View pricing
Clerk's logo

Newsletter!

The latest news and updates from Clerk, sent to your inbox.

Clerk logo

Clerk - Complete User Management

TwitterLinkedInGitHubDiscordFacebook

© 2022 Clerk Inc.


product
Features

© 2022 Clerk Inc.