乐闻世界logo
搜索文章和话题

Next.js 13: How to Pass Data from Middleware to Components?

2024年7月18日 01:18

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:

  1. Create or modify the middleware: In the middleware.ts file of your Next.js application, process requests and respond using the NextResponse object. Here, you can set the data that will be passed to components.

  2. 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 NextResponse object.

    typescript
    import { 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; }
  3. Retrieve data in components: In Next.js pages or components, read the response headers or cookies set in step 2 using getServerSideProps or getStaticProps (depending on the data fetching method for the page).

    typescript
    export 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.

标签:Next.js