0
0
NextjsDebug / FixBeginner · 3 min read

How to Fix 404 Error on Refresh in Next.js

The 404 error on refresh in Next.js happens because the server does not recognize client-side routes. To fix this, ensure you use next.config.js with proper rewrites or deploy on platforms that support Next.js routing natively like Vercel.
🔍

Why This Happens

Next.js uses client-side routing for pages inside the pages/ directory. When you refresh a page or enter a URL directly, the server tries to find a matching file or route. If it doesn't exist on the server, it returns a 404 error.

This happens because the server does not know about the client-side routes handled by Next.js.

javascript
import { useRouter } from 'next/router';

export default function Page() {
  const router = useRouter();
  return <div>Current page: {router.asPath}</div>;
}

// If you refresh /about, server looks for /about.html or /about/index.html and fails, causing 404.
Output
404 - Page Not Found
🔧

The Fix

To fix the 404 on refresh, you can deploy your Next.js app on platforms like Vercel that handle routing automatically. If you use a custom server or static hosting, configure rewrites to serve _next/static and fallback to index.html for client-side routes.

For example, in next.config.js, add rewrites to redirect all unknown paths to / so Next.js can handle routing:

javascript
module.exports = {
  async rewrites() {
    return [
      {
        source: '/:path*',
        destination: '/',
      },
    ];
  },
};
Output
Next.js app loads correctly on refresh without 404 errors.
🛡️

Prevention

Always deploy Next.js apps on platforms that support its routing, like Vercel or Netlify with proper configuration.

When using custom servers or static exports, configure rewrites or fallback pages to avoid 404 on refresh.

Use Next.js built-in routing and avoid manual server routing unless necessary.

⚠️

Related Errors

Other common routing errors include:

  • 404 on dynamic routes: Ensure dynamic routes are correctly defined with brackets, e.g., [id].js.
  • Static export 404: Use next export carefully; static export does not support dynamic routes without fallback.
  • API route 404: Check API routes are inside pages/api and deployed correctly.

Key Takeaways

Next.js 404 on refresh happens because the server can't find client-side routes.
Use rewrites in next.config.js or deploy on Vercel to fix refresh 404 errors.
Avoid custom servers unless you handle routing correctly for all paths.
Dynamic routes must be properly defined to avoid 404 errors.
Static exports need fallback handling for dynamic routes.