1

I’m building a static site in Next.js. As static sites produce pages with the .html extension, I’m using the as attribute on my Link elements, which allow my pages to be reloaded.

I have now introduced the use of query strings to my URL’s so that, when the pages are reloaded, they remember what content to display, by use of the getInitialProps() method.

So far, so good, BUT ONLY DURING DEVELOPMENT.

The problem I face is, when the site is exported out as the static version, Next.js fails to call the getInitialProps() method, hence, when the browser is refreshed, my pages no longer know what to display.

Can anybody help with any of the following:

  1. Is there another way to allow static pages to be refreshed, without the use of the .html extension?
  2. Is there a way to ensure that the getInitialProps() method is called when exporting a static site and when reloading a page?
  3. Is there another way in which I can retrieve the query string from the browser URL, as Next.js doesn’t seem to have the ability to access even the top level window object?
Nimantha
  • 6,405
  • 6
  • 28
  • 69
MoO
  • 125
  • 1
  • 1
  • 9

1 Answers1

2

getInitialProps is only available on server-side rendered apps. It runs during development because Next doesn't know if you want your pages to be static or SSR. But when you run next build && next export, they become static and getInitialProps no longer runs. I believe this is also why next switched to getServerSideProps and getStaticProps instead of getInitialProps (for everything but the _app.js page)

In response to your list of questions:

  1. Next exports so that you don't have to use/show the HTML extension, but that also depends on your hosting setup. Exporting a static site exports .html files, but it's up to your hosting configuration to determine whether or not those are shown.
  2. See above and no - there is no way to have getInitialProps run on a fully static, exported site. You'd need to switch to a server-side rendered site if you have to use getInitialProps.
  3. Your static site can retrieve the query string, but it's not going to have it at build time. Instead, you'd need to check for it (usually in React.useEffect) when the window object is available. On a static site, that's not at buildtime but only at runtime. Check out this answer on how to get the query string in javascript - you can use this in your useEffect.
I'm Joe Too
  • 5,468
  • 1
  • 17
  • 29
  • 1
    This is so spot on and so clear, thank you. 1) I will be trying this first, as it seems the least painful. 2) Understood - makes sense and helps with my wider understanding. 3) I've just tested this (not that I don't trust you) and can see the `window` object, so this is my backup plan. – MoO Jul 14 '21 at 05:03