question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Inconsistent behaviour of `request.nextUrl.href`

See original GitHub issue

What version of Next.js are you using?

12.0.4

What version of Node.js are you using?

16.13.0

What browser are you using?

Chrome

What operating system are you using?

macOS

How are you deploying your application?

next start

Describe the Bug

I’m attempting to use Middleware to force a default locale in my application URLs, using example code from the documentation.

This worked when accessing the application through localhost, but when accessing using any other hostname, request.nextUrl.href contains the full URL. I’m not sure whether this is expected behaviour, but it seems like it could be a bug as this breaks the example code provided in the documentation.

Expected Behavior

For request.nextUrl.href to behave consistently. Either return the full URL, or the application path. Ideally the latter, as the example indicates this would be expected behaviour.

To Reproduce

Take this simple middleware:

import type { NextFetchEvent, NextRequest } from 'next/server'

export function middleware(request: NextRequest, event: NextFetchEvent) {
  return new Response(request.nextUrl.href)
}

curl the app using localhost, see the following:

$ curl http://localhost:3000/hello
/hello

But when using any other IP or hostname:

$ curl http://127.0.0.1:3000/hello
https://127.0.0.1:3000/hello

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Reactions:2
  • Comments:5

github_iconTop GitHub Comments

4reactions
marcoaciernocommented, Dec 5, 2021

This doesn’t seem to be fixed @Kikobeats? I am using next@12.0.7 and on Vercel req.nextUrl.href seems to be an absolute URL while it is a relative URL on Localhost

I am using: https://nextjs.org/docs/advanced-features/i18n-routing#prefixing-the-default-locale


export function middleware(req: NextRequest, _ev: NextFetchEvent) {
  const shouldHandleLocale =
    !PUBLIC_FILE.test(req.nextUrl.pathname) &&
    !req.nextUrl.pathname.includes("/api/") &&
    req.nextUrl.locale === "default";
  const locale = getLocale(req.cookies.pyconLocale);

  console.log("req.nextUrl.href =>", req.nextUrl.href)
  return shouldHandleLocale
    ? NextResponse.redirect(`/${locale}${req.nextUrl.href}`)
    : undefined;
}

const getLocale = (cookie: string): string => {
  if (cookie && VALID_LOCALES.findIndex((e) => e === cookie) !== -1) {
    return cookie;
  }

  return DEFAULT_LOCALE;
};

Going to https://pycon-git-web-167-use-nextjs-intl-system-python-italia.vercel.app/ redirects tohttps://pycon-git-web-167-use-nextjs-intl-system-python-italia.vercel.app/enhttps:/pycon-git-web-167-use-nextjs-intl-system-python-italia.vercel.app/default

This is the code:

More:

  ~/projects/pycon/backend on   WEB-167-use-nextjs-intl-system *12 !4 ❯ curl -I https://pycon-git-web-167-use-nextjs-intl-system-python-italia.vercel.app/
HTTP/2 302
date: Sun, 05 Dec 2021 13:02:41 GMT
content-type: text/plain
x-robots-tag: noindex
location: /enhttps:/pycon-git-web-167-use-nextjs-intl-system-python-italia.vercel.app/default
server: Vercel
x-vercel-id: fra1::mjftx-1638709361021-e0c75daacf94
strict-transport-security: max-age=63072000; includeSubDomains; preload
cache-control: public, max-age=0, must-revalidate
x-vercel-cache: MISS

====

Logs from Vercel

req.nextUrl.href => https://pycon-git-web-167-use-nextjs-intl-system-python-italia.vercel.app/default

req.nextUrl:

{ 
    hash: '',  
    searchParams: {},  
    search: '',  
    pathname: '/default'
    port: ''
    hostname: 'pycon-git-web-167-use-nextjs-intl-system-python-italia.vercel.app'
    host: 'pycon-git-web-167-use-nextjs-intl-system-python-italia.vercel.app'
    password: ''
    username: ''
    protocol: 'https:'
    origin: 'https://pycon-git-web-167-use-nextjs-intl-system-python-italia.vercel.app'
    href: 'https://pycon-git-web-167-use-nextjs-intl-system-python-italia.vercel.app/default'
    _options:    { basePath: ''
       headers:       { accept: '*/*'
          'accept-encoding': 'gzip, deflate, br'
          'accept-language': 'en-GB,it;q=0.5'
          'cf-ew-script-hash': '1.769f1d7b3e1996f0801f1e96cec9104ebf83819678da4655e3a9022e2a520aec.vercel'
          connection: 'Keep-Alive'
          cookie: 'pyconLocale=default'
          'deployment-url': 'pycon-cdkb50fs9-python-italia.vercel.app'
          forwarded: 'for=152.37.76.72;host=pycon-git-web-167-use-nextjs-intl-system-python-italia.vercel.app;proto=https'
          'forwarded-for': '152.37.76.72'
          host: 'pycon-git-web-167-use-nextjs-intl-system-python-italia.vercel.app'
          'max-duration': '5000'
          referer: 'https://pycon-git-web-167-use-nextjs-intl-system-python-italia.vercel.app/enhttps:/pycon-git-web-167-use-nextjs-intl-system-python-italia.vercel.app/default'
          'sec-fetch-dest': 'empty'
          'sec-fetch-mode': 'cors'
          'sec-fetch-site': 'same-origin'
          'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:94.0) Gecko/20100101 Firefox/94.0'
          'x-forwarded-for': '152.37.76.72'
          'x-forwarded-host': 'pycon-git-web-167-use-nextjs-intl-system-python-italia.vercel.app'
          'x-forwarded-proto': 'https'
          'x-middleware-preflight': '1'
          'x-real-ip': '3.8.152.17'
          'x-vercel-edge-region': 'lhr'
          'x-vercel-id': 'lhr1::qrz77-1638709680500-32d798092336'
          'x-vercel-ip-city': 'Hendon'
          'x-vercel-ip-country': 'GB'
          'x-vercel-ip-country-region': 'ENG'
          'x-vercel-ip-latitude': '51.5943'
          'x-vercel-ip-longitude': '-0.2491' }
       i18n:       { locales: [Object]
          defaultLocale: 'default'
          localeDetection: false }
       trailingSlash: undefined }
    _basePath: ''
    _url:    { 
        hash: '',
       searchParams: {},
       search: '',
       pathname: '/',
       port: '',
       hostname: 'pycon-git-web-167-use-nextjs-intl-system-python-italia.vercel.app',
       host: 'pycon-git-web-167-use-nextjs-intl-system-python-italia.vercel.app',
       password: '',
       username: '',
       protocol: 'https:',
       origin: 'https://pycon-git-web-167-use-nextjs-intl-system-python-italia.vercel.app',
       href: 'https://pycon-git-web-167-use-nextjs-intl-system-python-italia.vercel.app/,
    },  
       _locale:    { path: { pathname: '/', detectedLocale: 'default' }
       domain: undefined,
       defaultLocale: 'default',
       locale: 'default',
       redirect: undefined,
       trailingSlash: false,
    } 
}

In case it helps anyone:

export function middleware(req: NextRequest, _ev: NextFetchEvent) {
  const shouldHandleLocale =
    !PUBLIC_FILE.test(req.nextUrl.pathname) &&
    !req.nextUrl.pathname.includes("/api/") &&
    req.nextUrl.locale === "default";
  const locale = getLocale(req.cookies.pyconLocale);

  return shouldHandleLocale
    ? NextResponse.redirect(`/${locale}${req.nextUrl.pathname.replace("/default", "")}`)
    : undefined;
}

this is what I did to fix the middleware code: req.nextUrl.pathname.replace("/default", "")

2reactions
ndavidson-manticorecommented, Jan 12, 2022

I agree that this issue is not closed out and was wrongly marked as such. I am still having inconsistent behavior with the request nextUrl object and even the request.url string. @Kikobeats

Read more comments on GitHub >

github_iconTop Results From Across the Web

NextJs app API behaves inconsistent on Vercel - Stack Overflow
To resolve NextJs inconsistency on Vercel issue, you can try following ... and Inconsistent behaviour of request.nextUrl.href.
Read more >
Solved: "rel" pagination header broken when listing course...
Solved: When requesting a list of courses from the API, the "Link" header comes incomplete for some reason. (URL of my instance changed...
Read more >
django-allauth Documentation - Read the Docs
This application will contain your customized urls.py, views.py and provider.py files. The behaviour that can be customized is beyond the scope of this ......
Read more >
Known issues with Microsoft Graph
This article describes known issues and limitations with Microsoft Graph and provides workarounds when possible.
Read more >
Redfish Specification - DMTF
9.2.4 OData service and metadata document requests. ... nextLink ) property shall adhere to the rules in the Next link property clause.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found