jakeburden / next-absolute-url

Get the absolute URL of your Next.js app (optionally set a localhost dev URL)
300 stars 30 forks source link

ReferenceError: req is not defined #15

Open chrishrtmn opened 4 years ago

chrishrtmn commented 4 years ago

I'm running into this error when I try to add this via npm as a package, as well as tried the guide on https://codeconqueror.com/blog/get-the-current-url-in-next-js listed in the README.

Since the npm package wasn't working for me, the following is from the guide to manually troubleshoot it. From what I understand, it should be checking for 'req' under the host variable in the absolute-url file, else do 'window.location.host' but not having much luck.

I'm new to React/Next.js so it's probably something simple I overlooked but would be appreciative if someone can look at this.

// PROJECT/lib/absolute-url.js

function absoluteUrl(req, setLocalhost) {
  let protocol = 'https:'
  let host = req
    ? req.headers['x-forwarded-host'] || req.headers['host']
    : window.location.host

  if (host.indexOf('localhost') > -1) {
    if (setLocalhost) host = setLocalhost
    protocol = 'http:'
  }

  return {
    protocol: protocol,
    host: host,
    origin: protocol + '//' + host,
  }
}

// PROJECT/components/layout.js

import absoluteUrl from '../lib/absolute-url'

const { protocol, host } = absoluteUrl(req, 'localhost:3000')

export default function Layout({ children, pageTitle, description, ...props }) {
  return (
    <>
      <CONTENT>
    </>
  )
}
leocrapart commented 4 years ago

The 'req' parameter is given by the 'getStaticProps' method : you can get it this way :

export async function getStaticProps({ req }) { const { protocol, host } = absoluteUrl(req, 'localhost:3000')

Then you can use this to give an absolute url to the fetch method or other purpose

giovannipds commented 4 years ago

Next has updated its data fetch method and now getStaticProps doesn't return req anymore. getStaticProps is defined to be used for static generation only now. Alternative, you can use getServerSideProps to have access to req and then use absoluteUrl. See https://nextjs.org/docs/basic-features/data-fetching#getstaticprops-static-generation for details.

jesperordrup commented 3 years ago

Alternative, you can use getServerSideProps to have access to req and then use absoluteUrl.

But then its not a static page anymore :-)