Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ReferenceError: req is not defined #15

Open
chrishrtmn opened this issue Jun 6, 2020 · 3 comments
Open

ReferenceError: req is not defined #15

chrishrtmn opened this issue Jun 6, 2020 · 3 comments

Comments

@chrishrtmn
Copy link

chrishrtmn commented Jun 6, 2020

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
Copy link

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
Copy link

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
Copy link

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

But then its not a static page anymore :-)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants