Search code examples
reactjsnext.jsserver-side-renderingmiddlewarenext.js13

How to update request body in Next 13 using middleware.ts?


I want to rewrite request body in NEXT 13 using middleware function:

import { NextRequest, NextResponse } from 'next/server';

enum MiddlewareRoutes {
    ACCESS = '/api/access',
}

const middlewareHandler = async (
    route: MiddlewareRoutes,
    response: NextResponse
): Promise<NextResponse> => {
    switch (route) {
        case MiddlewareRoutes.ACCESS: {
            response.cookies.set({
                name: 'vercel',
                value: 'fast',
                path: '/',
            });
            return response;
        }
        default: {
            return response;
        }
    }
};

export async function middleware(request: NextRequest) {
    const response = NextResponse.next();
    request.headers.set('ABC', 'DEG');
    request.body = { hello: 'world' };
    const newResponse = await middlewareHandler(
        (request?.nextUrl?.pathname ?? '') as MiddlewareRoutes,
        response
    );
    return newResponse;
}

export const config = {
    matcher: ['/api/:path*'],
};

But I get error saying request is read-only property. How can I manipulate request body in NEXT 13?


Solution

  • you cannot update the request body. you can only update the headers. from this github post

    // pages/api/hello.ts
    export default (req, res) => {
      const valueFromMiddleware = req.headers['x-hello-from-middleware']
      return res.send(valueFromMiddleware)
    }
    
    // middleware.ts
    import { NextRequest, NextResponse } from 'next/server'
    
    export default function middleware(request: NextRequest) {
      // Clone request headers
      const headers = new Headers(request.headers);
      // Add a new request header
      headers.set('x-hello-from-middleware', 'foo');
      // Delete a request header from the client
      headers.delete('x-from-client');
    
      const resp = NextResponse.next({
        // New option `request.headers` which accepts a Headers object
        // overrides request headers with the specified new ones.
        request: {
          headers
        }
      });
    
      // You can still set *response* headers to the client, as before.
      resp.headers.set('x-hello-client', 'bar');
      return resp;
    }