-
Notifications
You must be signed in to change notification settings - Fork 27.6k
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
getInitialProps not working with history (back button)? #3065
Comments
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 You need both Example:
@liweinan0423 @anselmdk Are you using custom routing? |
I think our issue is that we use one central dispatcher ( <Link
href="/dispatcher"
as="/page/about"
>
<a>home</a>
</Link> The 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 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 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 |
@anselmdk can verify this works for the I updated the
and you can use it like this |
Currently, using `as` will cause the router to think the URL is not changing in the case where you're re-rendering the same page with a different route. This would of course be an issue for custom servers only. This should be an invisible change for non-custom-server users, since `as` is defaulted to `url` if not set. This should resolve vercel#3065.
Currently, using `as` will cause the router to think the URL is not changing in the case where you're re-rendering the same page with a different route. This would of course be an issue for custom servers only. This should be an invisible change for non-custom-server users, since `as` is defaulted to `url` if not set. This should resolve vercel#3065.
I'm getting same error, tried to update to 6.1.1 but won't fix.
I've also tried with shallow but no success:
|
@HaNdTriX It works well inside App routing but not with external link. |
Guys, is there any cool solution or alternatives? It's a really block at my project.
When I update the profile avatar and navigate to external url(e.g. |
@OscarBengtsson I've just tested it again. Navigate back inside root url (internally): 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 @timneutkens Do you have an idea about how to solve this and get all browsers inline? |
If you are experiencing issue that
|
Currently, using `as` will cause the router to think the URL is not changing in the case where you're re-rendering the same page with a different route. This would most likely be an issue for custom servers which are using shallow routing. This should be an invisible change for non-custom-server users, since `as` is defaulted to `url` if not set. This should resolve #3065.
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 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. |
This comment has been minimized.
This comment has been minimized.
I'm wondering if you're using |
I don't know for sure what is this config. Quick search and found this: I'm using custom routing integrated with Express: const app = next({ dev, dir: './src' })
const handle = app.getRequestHandler()
const bodyParser = require('body-parser')
const cookieParser = require('cookie-parser')
const compression = require('compression');
const render = function(req, res, page) {
const parsedUrl = parse(req.url, true)
const { pathname, query } = parsedUrl
return app.render(req, res, page, query)
}
app.prepare().then(() => {
const server = express()
if (process.env.NODE_ENV === "production") {
server.use(compression());
}
server.get('/start/:id/:hash', (req, res, next) => render(req, res, '/step1'))
server.get('/next/:id/:hash', (req, res, next) => render(req, res, '/step2'))
}) |
having this issue with this work around appears to work but it does a full page reload which isn't ideal, any other solutions? Router.beforePopState(({ as }) => {
window.location.href = as;
window.location.reload();
return false
// returning true or false here doesnt seem to matter, new signature requires a boolean to be returned
}); |
I was having this error in my getInitialProps function at a line that used Error: I changed this line to use a url param, before: after: I haven't been using next.js for very long and I have no idea why this is happening. Dumping the ctx object contains everything it should when hitting the back button. |
I'm getting this same behavior (internal routing - within pages inside my Something to note. I also didn't have this problem when testing with github pages, but this showed up for us when we needed to move it to production in aws s3 (I pitched |
If anyone runs into this issue in the future, I found a not-so-pretty solution. I'm not sure why If you add Diff import { withRouter } from 'next/router'
import Link from 'next/link'
const custom_link = ({ href, router, children, name, as }) =>
- <Link prefetch href={href} as={as} passHref>
+ <Link prefetch href={href} as={as + ".html"} passHref>
{children}
</Link>
export const CustomLink = withRouter(custom_link)
This works as it forces the server to serve the html file for the page instead of referring to the router which has lost its context... from what I gather. Hope this helps someone who's in a bind and needs a quick fix. Not an ideal solution, but eh... |
Why is this closed ? :( |
just encountered this. this should not be closed |
Same issue here on Safari 13 (Technology Preview) |
Also experiencing this with Safari. Chrome works as expected. If anything the different behaviors in the two browsers should be treated as an issue in and of itself (ie: The point @HaNdTriX made about bfcache) |
This issue is in Firefox, Chrome when using Next 9.1.6. This needs to be reopened. |
This hack works for now, but please let me know if anyone has a good solution or cause for this problem. static async getInitialProps(context) {
//Hack: If this code is executing in client-side, just reload.
if (process.browser) {
history.go();
}
...
return { ... };
} |
Is there a workaround that does NOT cause SSR? We‘d like to keep unnecessary SSR low because of backend resources. |
This is still an issue for me - for all browsers. |
Getting issue in Chrome and Next 9.2.1. |
Issue exists in firefox, experienced when using the forward button too, currently using the hack to get around it but would like a better solution, maybe one of the Router.events can be of some use? will investigate too Edit: used context to get around the issue completely as it fell into my use case, picking values from context while transitioning and taking value from query and setting into context to use when page is reloaded or back/forward buttons pressed |
Issue in Safari still |
Upgrading to 9.3.0 and changing getIntialProps to getServerSideProps solved the problem. |
It really did solve it, thanks :) |
Awesome, worked for me but |
I'm running a legacy project on |
There haven't been breaking changes in the latest releases. |
for searchers finding this issue, here's another possible cause of the back button not working, i was using |
In app.ts, execute the following statement on componentDidMount. // app.ts
this.props.router.beforePopState(({ as, options }) => {
if (options.shallow) {
this.props.router.replace(as)
return false
}
return true
}) |
This worked for me! Thank you @f2hard3 ! |
Hello, I'm having this exact same issue with Router.push and an componentDidMount kind of useEffect. What is the recommended solution for a client-side rendering flow? |
This issue has been automatically locked due to no recent activity. If you are running into a similar issue, please create a new issue with the steps to reproduce. Thank you. |
I have an app with a single page
index.js
, and I parse the query parameters ingetInitialProps
: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 returnscreenId: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?
The text was updated successfully, but these errors were encountered: