Blog>
Snippets

Optional Dynamic Routes

Demonstrate the use of optional catch-all routes to create complex routing scenarios with optional path segments.
import { useRouter } from 'next/router';

export default function Page() {
  const router = useRouter();
  const { slug } = router.query;
  // slug is an array of the path parameters

  return (
    <div>
      <p>Path segments:</p>
      {slug?.map((segment, i) => (
        <span key={i}>{segment}{' '}</span>
      ))}
    </div>
  );
}

//  The file name should be [...slug].js for optional catch-all routes
This code demonstrates a Next.js page component that uses an optional catch-all route. The file name for this page should be [...slug].js to handle any sub-path under its directory, with 'slug' being an array containing the (optional) path segments.
const express = require('express');
const router = express.Router();

router.get('/user/:id?', function(req, res) {
  const userId = req.params.id;
  if (userId) {
    res.send(`User ID is ${userId}`);
  } else {
    res.send('User ID is not specified');
  }
});

module.exports = router;

// The question mark after the ':id' parameter makes it optional
This code snippet shows a basic Express.js route with an optional parameter. It defines a GET route where the ':id' part of the path '/user/:id?' is optional. If supplied, it will echo the user ID, otherwise it will return a message indicating that the ID is not specified.