How to Fix 404 Error on Refresh in Next.js
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.
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.
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:
module.exports = { async rewrites() { return [ { source: '/:path*', destination: '/', }, ]; }, };
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 exportcarefully; static export does not support dynamic routes without fallback. - API route 404: Check API routes are inside
pages/apiand deployed correctly.