I'm new to next.js and as a first step, before I start developing the actual app, I'm following the docs to learn the basics, and right now, I'm struggled trying to get the prefetch working, since all the preloaded requests are returning 404 error.
So what's wrong with my code? How can I solve this problem?
The demo repository is on github.
Notice that only express
server knows how to process URL of this kind /post/:id
, next.js
doesn't know it so next.js
tries to prefetch unexistent pages (and you may see in the Chrome console output).
You may fix this behaviour easily: just need rewrite your links this way
<Link href={`/post/?id=${show.id}`} as={`/post/${show.id}`} prefetch>
As a result only one query to prefetch post.js
page will be executed.
This technique is called "route masking" you may read more about in in the Next.js tutorial
An update:
It seems that the question is more about how prefetch
feature actually works in Next.js so I will try to explain it.
Without prefetch
prop on the Link Next.js will load related chunk on demand (when a user clicks link) so it will cause a small delay to load and parse javascript. The prefetch
prop allows you to remove this delay because javascript will be loaded as soon as possible after application start. In both cases new page will be rendered in the browser like in a usual React app.
Don't use this: import Link from "next/link";
Use: import { Link } from './routes';
This is the routes.js configuration file
My routes.js:
const routes = (module.exports = require("next-routes")());
routes.add("/:username", "profilepage");
Using :
import { Link } from './routes';
<Link route={"/my_page"}><a href="my_page">My Page</a></Link>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With