javascript - How to get the FULL url from the API route in nextjs - Stack Overflow

I am wondering if there's a way for me to get the full URL of the current request inside the API r

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. ";

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/api/test"

Share Improve this question edited Feb 28, 2022 at 16:59 Toxnyc asked Feb 28, 2022 at 15:49 ToxnycToxnyc 1,37012 silver badges20 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 5

I see two options here.

Option 1

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

  • 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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745345373a4623520.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信