Next.js dynamic route - 404 on page reload after added SLUG

Viewed 5133

I'm used Next.js and Node.js for my project.

What we have: Pages structure:

pages/products/PageSomeName.js

pages/products/PageEnotherName.js

pages/products/PageName.js

Pages name in products folder is can be different

routes.js

routes.add("/products/:id", "/products/[id].js");

server.js

app.prepare().then(() => {
  const server = express();

  server.use(
    "./images",
    express.static(path.join(__dirname, "images"), {
      maxAge: dev ? "0" : "365d"
    })
  );

  server.use(bodyParser.json());

  server.get("*", (req, res) => {
    return handle(req, res);
  });

  const PORT = process.env.PORT || 9001;

  server.listen(PORT, err => {
    if (err) throw err;
    console.log(`> Read on http://${process.env.SITE_URL_FULL}`);
  });
});

Link component

 <Link href={`/products/${data.link}`} as={`/products/${data.slug}`}/>

data array

export const storeProducts = [
  {
    id: 1,
    title: "Title1",
    link: "product_name_some",
    slug: "product-1-slug",
  },
  {
    id: 2,
    title: "Title2",
    link: "product_name_different_some_name",
    slug: "product-2-slug"
  },

There was a problem when I added slug for my links.

By client side everything works fine. I take localhost:3000/product-2-slug in browser url. But after reload, I take 404 error page from Next.js

What I must added by server side in server.js for normal server reloading? Maybe I need change Link component or next-route settings in routes.js

Thanks!

1 Answers

In server.js you should have a routes as below.

server.get("/products/product1", (req, res) => {
    return handle(req, res);
});
server.get("/products/product2", (req, res) => {
    return handle(req, res);
});
server.get("/products/product3", (req, res) => {
    return handle(req, res);
});

A good way to handle the same is to create a generic products.js inside the pages directory and on server handle as below.

server.js

server.get("/products/:id", (req, res) => {
    return handle(req, res, { id: req.params.id });
});

and in

pages/products.js we can create a getInitialProps method

static getInitialProps (context) {
    // parameters reqturned from server are accessible via
    const id = ctx.query.id
}
Related