5

How can I modify the request object in Next.js middleware file?

I have seen this question but it does not answer my question.

I have a middleware file that looks like below:

// middleware.js    
export function middleware(request: NextRequest) {
    req.name = "foo";
    //If I console.log req.name I see it is equal to foo.
    console.log(req.name) // logs "foo"
}

Then I have an api route like below

// pages/api/hello.js
export default async function handler(req, res) {
    console.log( req.name ) //logs undefined
    // what can I do so that I can access the new properties
    // I put in the req object in the middlware file here?
}
YulePale
  • 6,688
  • 16
  • 46
  • 95
  • haha, all my googled questions lead me to your questions here on Stackoverflow. I think we have the same problem. I wanted to find a way how to add `app.use` in the other question now i found this one where you asked the same thing i thought it would work. So, while we cant use `app.use` in Nextjs i thought there must be a way to modify the `req` object. Did you find a solution for this? – Ilir Dec 31 '22 at 12:05
  • 1
    Nope, I did not find a way :). I just used next-connect. – YulePale Jan 02 '23 at 14:28

1 Answers1

0

As of NextJs v 13.0.0 there is a workaround setting headers https://nextjs.org/docs/advanced-features/middleware

//middleware.js
import { NextResponse } from 'next/server'

export async function middleware (req, res) {
  // NextJs doesn't allow you to modify the request object. So the only way to pass the data to the client is to add it to the headers of a new request.
  const requestHeaders = new Headers(req.headers)
  requestHeaders.set('xname', "foo")

  // And the middleware expects a response object as a return so we need to involve that as well.
  const response = NextResponse.next({
    request: {
      // New request headers
      headers: requestHeaders
    }
  })

  return response
}

In the api you can access the header

// pages/api/hello.js
export default async function handler(req, res) {
    const nameHeader = req.headers.xname
    console.log('Hello '. nameHeader) // Hello foo
}

You can also set the header to a JSON object if you want to pass more data this way, but Id recommend being a bit restrictive to keep the size of the header down and avoiding 431 errors 'Request header fields too large'

codeSmith
  • 1
  • 1