Next.js 13: How to Pass Data from Middleware to Components?
In Next.js 13, you can pass data from middleware to components using the new Middleware and Edge Runtime features. The specific steps are as follows:
-
Create or modify the middleware: In the
middleware.tsfile of your Next.js application, process requests and respond using theNextResponseobject. Here, you can set the data that will be passed to components. -
Set response headers or cookies: In the middleware, pass data by setting response headers or cookies. For example, serialize computed or fetched data into a JSON string and set this string as a response header or cookie in the
NextResponseobject.typescriptimport { NextResponse } from 'next/server'; export function middleware(request) { const data = { user: 'John Doe', age: 30 }; const response = NextResponse.next(); response.headers.set('X-Custom-Data', JSON.stringify(data)); return response; } -
Retrieve data in components: In Next.js pages or components, read the response headers or cookies set in step 2 using
getServerSidePropsorgetStaticProps(depending on the data fetching method for the page).typescriptexport async function getServerSideProps({ req }) { const data = req.headers['x-custom-data']; const parsedData = JSON.parse(data); return { props: { userData: parsedData } }; }
By using this approach, you can safely and effectively pass data from middleware to your React components, leveraging Next.js's new architecture and features.