getInitialProps not working with history (back button)?
I have an app with a single page index.js, and I parse the query parameters in getInitialProps:
static async getInitialProps ({query}) {
console.log('PAGE', query.screenId);
try {
const projectData = await ProjectLoader.loadProject(query);
return projectData;
}
catch (err) {
console.error(err);
}
};
I use <Link href={pathname, query} prefetch> tags to build my links.
The screenId property is key to finding the right page to render.
However, when I use the back button in the browser to a page without screenId set, getInitialProps doesn’t return screenId:undefined as expected, but another value (as you can see in the console log):
When I refresh the page, I get the right properties and see the correct results.
The “imaginary” screenId is actually a valid value, but I have no idea where this value comes from.
Why is this happening?
This is interesting to me as I am facing a similar issue with "back button". Could you try using the latest version of next.js and share your repo if possible?
We're facing similar issues, any pointers would be appreciated.
This may not be the solution to the above problem, but the last few days I had a big “a-ha” moment with the <Link> component when you’re using custom routing:
You need both href and as properties, they both need to be valid, and they will most likely to be different from each other(!).
Example: <Link href={'/mynextjspage?articleId=' + articleId} as={'/articles/' + articleId}>
as will be the link as you want it to appear, while href will be a reference to a Page component in the /pagesfolder with parameters added as a query string.
@liweinan0423 @anselmdk Are you using custom routing?
I think our issue is that we use one central dispatcher (pages/dispatcher.js). The dispatcher decides which components to load, based on the url (we're loading data from an API behind the scenes).
This works perfectly until we start hitting the browser's "back" button. Then you're redirected to a random page. It seems like the issue is that our links look like this:
<Link
href="/dispatcher"
as="/page/about"
>
<a>home</a>
</Link>
The href is always set to /dispatcher on all pages.
I've looked a little into other issues, and it seemed like the solution mentioned here would solve it. In short the idea is to append a unique query string, which would then make href look like something like this: /dispatcher?pretty=url1. Unfortunately that triggers another problem - the links just stop working (clicking them does nothing). I've isolated the issue by taking the code from https://github.com/zeit/next.js/tree/master/examples/parameterized-routing and making it run on one file only:
import React from 'react'
import Link from 'next/link'
export default class extends React.Component {
static getInitialProps ({ query }) {
return { id: query ? query.id : 'error'}
}
render () {
return <div>
<h1>My {this.props.id} blog post</h1>
<ul>
<li><Link href='/test?id=first' as='/test/first'><a>My first blog post</a></Link></li>
<li><Link href='/test?id=second' as='/test/second'><a>My second blog post</a></Link></li>
<li><Link href='/test?id=third' as='/test/last'><a>My last blog post</a></Link></li>
</ul>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua.
</p>
</div>
}
}
Clicking any of the three links does nothing. When the query strings are removed from the links (so href only contains /test) it works fine again - unless the history part. A funny observation is that when after removing them you add them back in, and the component is hot reloaded, both links and history work - until you refresh the page.
I hope anyone's had similar issues and/or can point us into a direction for solving this.
I am having the same issue..
Same here.
Does anyone solved this problems?
@anselmdk / @tomsoderlund are you using a custom server to handle that sort of routing? Might be helpful to see that as well.
So, because nobody answered, neither here nor on Slack, we solved this issue by creating a custom version of link.js.
I think all we did was to change https://github.com/zeit/next.js/blob/canary/lib/link.js#L75
to Router[changeMethod](href + '?uri=' + as, as, { shallow }).
Feels a bit hacky, but it works :)
@anselmdk can verify this works for the Link component, but if using Router.push/replace the issue still persists.
I updated the Router component with the following.
push(url, as = url, options = {}) {
return this.change('pushState', url + '?uri=' + as, as, options)
}
replace(url, as = url, options = {}) {
return this.change('replaceState', url + '?uri=' + as, as, options)
}
and you can use it like this Router.push('/', pathname)
I'm getting same error, tried to update to 6.1.1 but won't fix.
Also tried to set useFileSystemPublicRoutes: false and didn't changed anything on the app.
I'm redirecting this way in my app but once i hit the back button the component don't fire the getInitialProps:
const cartId = 20;
Router.push(`/step2?cartId=${cartId}&hashId=asd`, `/next/${cartId}/asd`)
I've also tried with shallow but no success:
Router.push(`/step2?cartId=${cartId}&hashId=asd`, `/next/${cartId}/asd`, { shallow: true })
Hey guys
I tried to reproduce your example but could not verify it.
Example:
Got you issue resolved in the meantime or did I do something wrong?
@HaNdTriX It works well inside App routing but not with external link.
If you navigate to external url(e.g. github) and click back button, you see getInitialProps is not called.
Guys, is there any cool solution or alternatives? It's a really block at my project.
class Profile extends React.Component {
// Update the profile avatar and show updated avatar
// Call api to update avatar at backend database
}
Profile.getInitialProps = () => {
// Call api to get profile information
}
When I update the profile avatar and navigate to external url(e.g. terms pdf url) and click back button, it shows the previous avatar as getInitialProps is not called.
Router.replace() after updating Avatar, didn't help me.
@OscarBengtsson I've just tested it again. ~~And it works from my point of view.~~
Navigate back inside root url (internally): getInitialProps is called on the client (client render).
Navigate back from external url (external): getInitialProps is called on the server (server render).
The initial request is always rendered on the server.
This is the intended behavior.
Edit: Nevertheless on chrome it works in Safari & Firefox not.
Ok I finally could reproduce the issue.
The issue is only existent in the browsers Safari & Firefox. These browsers use a feature called "bfcache" (back-forward cache). This means the html document is cached in memory. As soon as a user uses a back button coming from an external page, no request is made on the server. Instead the html document is rendered from the cache. Since getInitialProps already ran (before it was cached) it won't run again.
@timneutkens Do you have an idea about how to solve this and get all browsers inline?
If you are experiencing issue that getInitialProps not invoked when user click back between same pages you can use next code (somewhere during bootstrap on frontend):
Router.beforePopState(({url, as}) => {
Router.replace(url, as, {});
return false;
});
Guys, finally i've better understood my problem. Im using Next 7.0 canary to see if latest updates work.
Im my project im using custom routing and my first URL is /start/:id/:hash
When i change route to next/:id/hash it works correct
Router.push({
pathname: '/step2',
query: { id: cartId, hash: 'asd' }
}, `/next/${id}/${hash}`)
Once i got back using chrome back button the route stop working as expected, the initialProps doesn't receive the params vars, They do work in step2 that i've redirect but once popstate gets called it doesnt receive any params option, because it was the first rendered page and next router didn't received any options as first render...
To solve this im splitting url, it's temporally until i found a way to solve this.
@wallynm did you try my solution above? Looks very similar to what I faced.
@DontRelaX in the end i've discovered that using custom routing with params into URL like i've used Next can't understand and read those params at first render, so when user gets back using back button all params are empty because they weren't parsed, any time the Router received these params so it cant understand once it get popped from the browser history...
Your last comment helped me understand better the problem and to solve i've implemented this on the component did mount:
componentDidMount() {
const { store, id, hash } = this.props
Router.replace({
pathname: '/step1',
query: { id, hash }
}, `/start/${id}/${hash}`, { shallow: true})
}
This way at first render my first history gets replaced by one with custom defined params, as at first it can't understand which part of the url is what... When we redirect a user inside our app, we send those params and how the router should map the URL to the vars, but at first render... User came from an direct access.
In the end, i don't see this as a Next/Routing Bug but a misunderstood about how i was handling my custom variables...
And i think this could be very common for anyone working with these custom routes, very tricky to discover...
