Blog>
Snippets

Utilizing Wildcards for Catch-All Routes

Provide an example of using wildcards in routes to create a catch-all route for handling 404 or redirecting unspecified paths.
const express = require('express');
const app = express();

// Serve static files from the React app
app.use(express.static(path.join(__dirname, 'client/build')));

// The catch-all handler for all other requests
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname+'/client/build/index.html'));
});
This code snippet is for an Express.js server. It serves static files from a React app, and uses a wildcard route to catch all other GET requests. This way, any non-API requests are redirected to the React app, enabling client-side routing to handle the request.
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';

<Router>
  <Switch>
    {/* Define specific routes here */}
    <Route path='/about' component={About} />
    <Route path='/contact' component={Contact} />
    {/* Catch-all route */}
    <Route path='*' component={NotFound} />
  </Switch>
</Router>
This code snippet is for a React app using React Router for routing. It sets up a series of routes for specific paths (`/about`, `/contact`) and then uses a wildcard (`*`) route as a catch-all for any other paths, serving a NotFound component, which could be a 404 page or a redirect.