Paweł Baca
Paweł Baca

Reputation: 888

Next.js 404 error after refreshing the page

I try to learn Next.js but I have a small problem. Here is my test code:

import Link from 'next/link';
export default () => (
    <p>Hallo next <Link href="/abouts?id=2" as='/abouts/1'><a>About</a></Link></p>
)

If I clicked in link About from index.js page, my url look '/about/1/' and work fine, but if I refresh page I get error 404. If I type in browser /abouts?id=2" and refresh page everything works fine. Do u know how I can fix this ? I want have links like

/about/1/

Upvotes: 1

Views: 9756

Answers (2)

Puedes usar un archivo .htaccess, por ejemplo para un dominio xyz.com donde se creo un portal con nextjs puedes usar este archivo:

  RewriteEngine On  
  RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
  RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
  RewriteRule ^ - [L]

  RewriteRule ^ /index.html [L]

Upvotes: 0

Fabian Schultz
Fabian Schultz

Reputation: 18556

From the Next.js documentation:

The second as parameter for push and replace is an optional decoration of the URL. Useful if you configured custom routes on the server.

So to achieve this behavior, you'll need to configure custom routes inside your server.js—for example using express. Extend your server with this:

const next = require('next');
const express = require('express');

const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev });
const handle = app.getRequestHandler();

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

  // Nice permalinks for pages.
  // Sets up a custom route, that then uses next.js to render the about page.
  server.get('/about/:id', (req, res) => {
    const params = { id: req.params.id };
    return app.render(req, res, '/about', params);
  });

  // For all other routes, use next.js.
  server.get('*', (req, res) => {
    return handle(req, res);
  });

  server.listen(port, '0.0.0.0', err => {
    if (err) throw err;
    console.log(`${'\u2705'}  Ready on http://localhost:${port}`);
  });
});

Upvotes: 5

Related Questions