Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Next.js 404 error for all preloaded links

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.

enter image description here

like image 372
Lucas Silva Avatar asked Feb 03 '23 18:02

Lucas Silva


2 Answers

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. enter image description here

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.

like image 163
Andrei Belokopytov Avatar answered Feb 06 '23 08:02

Andrei Belokopytov


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>
like image 40
John Jaider Vanegas Avatar answered Feb 06 '23 09:02

John Jaider Vanegas