DEV Community

Cover image for Fixing Vercel 404 Errors: A Simple Solution for Node.js Projects
Elliot Brenya sarfo
Elliot Brenya sarfo

Posted on

Fixing Vercel 404 Errors: A Simple Solution for Node.js Projects

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:

  1. Creating a minimal vercel.json configuration file
{
  "rewrites": [
    {
      "source": "/(.*)",
      "destination": "/"
    }
  ],
  "buildCommand": "npm run build",
  "outputDirectory": "dist"
}
Enter fullscreen mode Exit fullscreen mode

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:

  1. First, I created a vercel.json file in my project root
  2. Added the minimal configuration shown above
  3. Pushed the changes to my GitHub repository
  4. In my Vercel dashboard, I went to Project Settings
  5. Under "Framework Preset", selected "Node.js"
  6. Redeployed the application

And just like that, all my routes started working perfectly! No more 404 errors on refresh.

What I Learn

  1. Less is more when it comes to Vercel configuration
  2. The framework preset selection is crucial for proper routing
  3. A simple rewrite rule can solve complex routing issues
  4. If you're facing similar 404 issues with your Vercel deployment, try this solution.
  5. It's worked wonders for my project, and I hope it helps you too.

Top comments (0)