I recently ran into a frustrating issue with my Node.js project deployed on Vercel where all routes except the home page (/) were returning 404 errors. After hours of debugging and searching through StackOverflow, I finally found a simple solution that I wanted to share with the community.
The Problem
My GitHub Activity Generator project was working perfectly fine locally, but after deploying to Vercel, any route refresh would result in a 404 error. The home page would load initially, but refreshing any other route would break the application. This is a common issue that occurs when the routing configuration isn't properly set up for single-page applications on Vercel.
The Solution
The fix turned out to be surprisingly simple. It involved two key steps:
- Creating a minimal vercel.json configuration file
{
"rewrites": [
{
"source": "/(.*)",
"destination": "/"
}
],
"buildCommand": "npm run build",
"outputDirectory": "dist"
}
Setting the Framework Preset to "Node.js" in the Vercel project settings.
Why This Works
The magic happens in the rewrites configuration. The catch-all route "source": "/(.*)" captures all incoming requests and redirects them to the root ("destination": "/"). This ensures that our Node.js application handles the routing instead of letting Vercel try to find static files for each route.
Implementation Steps
Here's how I implemented the fix:
- First, I created a vercel.json file in my project root
- Added the minimal configuration shown above
- Pushed the changes to my GitHub repository
- In my Vercel dashboard, I went to Project Settings
- Under "Framework Preset", selected "Node.js"
- Redeployed the application
And just like that, all my routes started working perfectly! No more 404 errors on refresh.
What I Learn
- Less is more when it comes to Vercel configuration
- The framework preset selection is crucial for proper routing
- A simple rewrite rule can solve complex routing issues
- If you're facing similar 404 issues with your Vercel deployment, try this solution.
- It's worked wonders for my project, and I hope it helps you too.
Top comments (0)