Sling Academy
Home/Next.js/Fixing Next.js Error: Blank Page or 404 on Refresh

Fixing Next.js Error: Blank Page or 404 on Refresh

Last updated: January 01, 2024

Understanding the ‘Blank Page or 404’ Error in Next.js

Encountering a ‘Blank Page or 404’ error on refresh in a Next.js project can be puzzling. This commonly occurs due to client-side routing being utilized within a single-page application (SPA) framework when the server doesn’t know how to handle direct accesses to these client-routed paths. Essentially, what happens is that when you refresh the page, the Next.js server tries to look for an actual page at that route, but since the route is often dynamically generated in the client, it fails to find it and returns a 404 error.

Solving the Error with Next.js Server-Side Configuration

To resolve this issue, it is essential to make sure that the server is properly set up to handle routing for your Next.js project. In the dev mode, Next.js handles this automatically, but in production, you need to configure your server to fallback to the index.html for handling these routes. This setup process will differ depending on the hosting service or server you are using. You can configure your custom server or utilize the ‘next start’ command if you’re running your build on a Node.js server.

Implementing a Custom Server in Next.js

For those who are using custom servers with Next.js, it is crucial to handle the routes yourself. To ensure the server can handle deep links, you need to rewrite the server’s response to serve the index.html file on each path hit that does not point to a static file. This can be achieved using frameworks like Express in combination with next.js. Here’s a simple method to set up a custom Express server that catches all undefined routes and directs them back to the index while serving other static files without interference.

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

const port = parseInt(process.env.PORT, 10) || 3000;
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();

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

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

  server.listen(port, (err) => {
    if (err) throw err;
    console.log("> Ready on http://localhost:" + port);
  });
});

Using next.config.js for Rewrites

You can also leverage the ‘next.config.js’ for redirecting traffic to the root ‘/’ route. Here’s a sample config file that ensures your Next.js app can handle page refreshes without showing a 404:

module.exports = {
  async rewrites() {
    return [
      {
        source: '/:path*',
        destination: '/',
      },
    ];
  },
};

Note that while this workaround can prevent 404 errors on reloads, it might interfere with API routes and dynamic routing if not properly managed. Make sure your API routes and dynamic paths are exempt from this rewriting rule or handled separately.

Static Export Considerations

For folks opting for static website generation with Next.js and encountering this issue, you might need to ensure all paths are exported properly during the ‘next export’. Dynamic routes not predefined could result in a 404 when accessed directly since the server has no HTML file associated with that path.

In conclusion, dealing with the ‘Blank Page or 404 on Refresh’ error in Next.js does not have a one-size-fits-all solution. You need to consider your deployment setup and choose the strategy that best aligns with your server configuration or hosting provider. Implementing custom server routing, adjusting your next.config.js, or ensuring proper static export can keep your Next.js app running smoothly even after a refresh.

Next Article: Fixing Next.js Error: Link is not defined

Previous Article: Fixing Next.js Issue: Duplicate Meta Description and Tags

Series: Common Errors in Next.js

Next.js

Related Articles

You May Also Like

  • Solving Next.js Image Component Error with CSS Classes
  • How to Use MUI (Material UI) in Next.js 14
  • Fixing Data Update Issues in Next.js Production
  • Fixing Next.js Undefined ENV Variables in Production Build
  • Solving Next.js SyntaxError: Unexpected token ‘export’
  • Next.js Error: Found Page Without a React Component as Default Export – How to Fix
  • Fixing Next.js Error: Blank Page on Production Build
  • Fixing Next.js Error when Importing SVGs: A Step-by-Step Guide
  • Next.js Issue: useEffect Hook Running Twice in Client
  • Fixing ‘self’ is not defined error in Next.js when importing client-side libraries
  • How to Dockerize a Next.js App for Production
  • How to set up Next.js with Docker Composer and Nginx
  • Solving Next.js CORS Issues: A Comprehensive Guide
  • Fixing Next.js Hydration Mismatch Error in Simple Ways
  • Next.js Error: Cannot use import statement outside a module
  • Next.js: How to Access Files in the Public Folder
  • Fixing Next.js Import CSS Error: A Simple Guide
  • Fixing LocalStorage Not Defined Error in Next.js
  • Fixing Next.js Error: No HTTP Methods Exported