Toxnyc
Toxnyc

Reputation: 1350

How to get the FULL url from the API route in nextjs

I am wondering if there's a way for me to get the full URL of the current request inside the API route (pages/api/myapi), the only returned response I see that's close to what I need is the req.headers.referer, but I am not sure if this value will always be in the headers. The type for that is string | undefined.

There's also the req.headers.host and req.headers.origin but it's missing the protocol.

The end goal is to get the full URL inside my API handler function.i.e. "https://example.org/api/test"

Upvotes: 5

Views: 4126

Answers (1)

Advena
Advena

Reputation: 2233

I see two options here.

Option 1

If the protocol is known (e.g. http or https), then combine

  • req.headers.host - returns the hostname with the portnumber, e.g. localhost:3000
  • req.url - returns the requested path, e.g. /api/test

Option 2

If the protocol is unknown, then we have to dig deeper to get the full URL. The req object exposes in the Symbol(NextRequestMeta) key the following values

{
  ...
  [Symbol(NextRequestMeta)]: {
    __NEXT_INIT_URL: 'http://localhost:3000/api/test',
    _protocol: 'http',

  }
}

There are several approaches for accessing Symbol's properties in an object. One example to access __NEXT_INIT_URL would be:

const nextRequestMeta = req[Reflect.ownKeys(req).find(
    (s) => String(s) === "Symbol(NextRequestMeta)"
)];
console.log(nextRequestMeta.__NEXT_INIT_URL); // -> http://localhost:3000/api/test

Upvotes: 5

Related Questions