Search code examples
next.jsgeolocation

Next.js: How to access geolocation information provided by middleware.js?


The Next.JS middleware feature allows for easy adding of geolocation based information to a request:

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

export function middleware(req) {
    const { nextUrl: url, geo } = req
    const country = geo.country || 'DE'
    url.searchParams.set('country', country)
    return NextResponse.rewrite(url)
}

How do I access this information from the code of a page? I am sure there is an easy way, and I was just not able to find it...


Solution

  • I just found a straight-forward solution.

    Make sure /pages/_app.js has the following lines in it (default if created with npx create-next-app):

    // /pages/_app.js
    
    function MyApp({ Component, pageProps }) {
      return <Component {...pageProps} />
    }
    

    Then the country (or other information added by the NextJS middleware can be accessed directly like this:

    let geoCountry = pageProps.country;