Table of Contents
What is Routing?
Routing determines how an application responds to a request for a specific URL. It maps URLs to code that handles the request, delivering the appropriate content.
Client‑Side Routing
Client‑side routing is handled in the browser, allowing single‑page applications (SPAs) to change views without a full page reload. Libraries like React Router or Vue Router manage this.
import { BrowserRouter, Routes, Route } from "react-router-dom";
function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
</BrowserRouter>
);
}
Server‑Side Routing
Server‑side routing resolves URLs on the server before sending a response. It’s common in traditional multi‑page apps and in frameworks like Express, Django, or Laravel.
const express = require('express');
const app = express();
app.get('/', (req, res) => res.send('Home Page'));
app.get('/about', (req, res) => res.send('About Page'));
app.listen(3000, () => console.log('Server running on :3000'));
Express Example
This minimal Express server demonstrates basic routing with parameters.
app.get('/users/:id', (req, res) => {
const userId = req.params.id;
// Fetch user from DB...
res.json({ id: userId, name: 'User '+userId });
});
React Router Example
Dynamic routes allow component rendering based on URL parameters.
function User() {
const { id } = useParams();
return <h2>User ID: {id}</h2>;
}
<Routes>
<Route path="/users/:id" element={<User />} />
</Routes>