Handling 404 Errors on Vercel Deployments: A Step-by-Step Guide with React, Vite, and react-router-dom
404: Not Found Error when deployed on Vercel
At times, deploying these single-page applications (SPAs) to production environments can sometimes reveal unexpected challenges. One common issue that many developers face is the dreaded “404 error” when deploying to platforms like Vercel. This error occurs when users try to access a specific route directly or refresh the page, resulting in a not-so-friendly “Page Not Found” message.
In this article, we’ll take you on a journey to overcome this hurdle. We’ll start by setting up a React project using Vite(a blazing-fast build tool), and then dive into adding client-side routing using react-router-dom. Finally, we’ll tackle the 404 error issue head-on and show you how to resolve it with Vercel’s powerful rewrite functionality.
Setting Up a React Project with Vite:
Install Node.js and npm on your machine if you haven’t already.
Open your terminal and navigate to the directory where you want to create your project.
Run the command
npm init vite@latest
to create a new Vite project. This will prompt you to enter a project name and select a framework and variant. Choose "React" as the framework and "JavaScript" as the variant.Once the project is created, navigate to the project directory and run
npm install
to install the project dependencies.Finally, run
npm run dev
to start the development server. Your React app should now be running athttp://localhost:5173
.
Adding Routing with react-router-dom:
React offers a fantastic library for handling routing called react-router-dom
. In this section, we'll integrate react-router-dom
into our React project created with Vite.
Before we can begin using react-router-dom
, we need to install it as a project dependency. Open your terminal and run the following command within your Vite-based React project directory:
npm install react-router-dom
This command will download and install the necessary packages to enable routing in our application.
Furthermore, to get started with react-router-dom
, we'll first define a basic routing structure. This typically involves creating different components for various pages or views and configuring routes for them.
Example, we can have this 👇 in our App component.
// src/App.jsx
import { BrowserRouter as Router, Routes, Route} from 'react-router-dom';
import Home from './components/Home';
import Contact from './components/Contact';
function App() {
return (
<Router>
<Routes>
<Route path="/" exact element={<Home/>} />
<Route path="/contact" element={<Contact/>} />
</Routes>
</Router>
);
}
export default App;
Now that we’ve set up the routing structure in the App component, let’s create the components for our home and contact pages. These components will be displayed when the user navigates to the respective URLs.
Below is an example of what the Home.jsx
and Contact.jsx
components might look like:
// src/components/Home.jsx
const Home=()=> {
return (
<div>
<h1>Welcome to the Home Page</h1>
{/* Add your home page content here */}
</div>
);
}
export default Home;
// src/components/Contact.jsx
const Contact=()=> {
return (
<div>
<h1>Contact Us</h1>
{/* Add your contact page content here */}
</div>
);
}
export default Contact;
With these components in place, we now have a basic routing structure for our SPA. When a user navigates to the root URL (‘/’), they will see the content of the Home
component, and when they navigate to '/contact', they will see the content of the Contact
component.
To enable navigation between routes, you can use Link
components from react-router-dom
. For example, you can add a navigation menu to your application like this:
// src/components/Navigation.jsx
import { Link } from 'react-router-dom';
const Navigation=()=> {
return (
<nav>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/contact">Contact</Link></li>
</ul>
</nav>
);
}
export default Navigation;
We can now import this Navigation
component into our App.jsx
component to provide users with an easy way to navigate between different views.
// src/App.jsx
import { BrowserRouter as Router, Routes, Route} from 'react-router-dom';
import Home from './components/Home';
import Contact from './components/Contact';
import Navigation from './components/Navigation';
function App() {
return (
<Router>
<Navigation/>
<Routes>
<Route path="/" exact element={<Home/>} />
<Route path="/contact" element={<Contact/>} />
</Routes>
</Router>
);
}
export default App;
With react-router-dom
integrated into your project, you now have a powerful tool for managing client-side routing in your React SPA.
However, there’s one crucial challenge that remains, which is handling the dreaded 404 error when deploying to Vercel.
The 404 Error Issue
This error occurs when a user tries to access a specific route directly or refreshes the page. In traditional server-rendered applications, the server handles route requests and serves the corresponding HTML pages. But in SPAs, routing is managed on the client-side, and the server may not be aware of these client-side routes. This discrepancy results in the server returning a “Page Not Found” error for direct route accesses, causing frustration for users and confusion for developers.
Using Vercel Rewrites
Vercel, our preferred deployment platform, provides a solution to this problem through its powerful “rewrites” functionality. Rewrites allow us to configure how incoming requests to our application’s URLs should be handled. With the right rewrite rules, we can ensure that all requests are redirected to the root URL, preventing the 404 error from occurring.
Procedures :
- Create a
vercel.json
File:
To define our rewrite rules, we need to create a vercel.json
file in the root directory of our project. This file serves as the configuration for our Vercel deployment.
// vercel.json
{
"rewrites": [
{
"source": "/(.*)",
"destination": "/"
}
]
}
In the above code, we defined a simple rewrite rule:
"source": "/(.*)"
: This source pattern matches any URL, capturing all incoming requests."destination": "/"
: It specifies that regardless of the incoming URL, it should be rewritten to the root URL (/
).
2. Deploy to Vercel:
Now that the rewrite rule has been configured, we can deploy our application to Vercel. You can do this through the CLI, by linking your Vercel account to your Git repository, or by deploying directly from your code repository.
vercel
If you have already deployed the project to vercel before and you didn’t use git repo, you can run this on your CLI
vercel --prod
Once the deployment is complete, access your application on Vercel using its assigned URL. Try navigating to different routes and refreshing the page — you’ll notice that the 404 error is no longer an issue. The rewrite rule ensures that all requests are redirected to the root URL, and your SPA’s client-side routing takes over from there.
Conclusion
Handling the 404 error on Vercel deployments for SPAs is a crucial step in providing a smooth and user-friendly experience. By integrating react-router-dom
for client-side routing and configuring Vercel rewrites, you've overcome this common challenge, ensuring that your application functions flawlessly in a production environment.