Skip to main content

Command Palette

Search for a command to run...

Mastering Dynamic URL Handling in Next.js 15 with Rewrites

Updated
3 min read
Mastering Dynamic URL Handling in Next.js 15 with Rewrites

As a frontend developer, I've encountered various challenges with routing in modern web applications. With the release of Next.js 15, I wanted to share a useful pattern I've implemented to handle location-based URL paths efficiently—without creating redundant pages.

The Challenge: Location-Based Content Without the Routing Mess

My application needed to display similar content for multiple locations, using URLs like:

  • /sell-your-car-in-kochi

  • /sell-your-car-in-tvm

  • /sell-your-car-in-kollam

The conventional approach would require creating separate pages for each location, leading to duplicated code and maintenance headaches. This is where Next.js rewrites come to the rescue.

Understanding Rewrites in Next.js 15

Rewrites allow you to map an incoming request path to a different destination path. Unlike redirects, rewrites don't change the URL in the browser, making them perfect for serving the same content under different URLs while preserving the original URL for SEO and user experience.

Implementing a Location-Based Content Solution

Step 1: Create Your Base Page

First, I created a single page component at app/sell-your-car/page.tsx that would serve as the template for all location variants:

// app/sell-your-car/page.tsx
import { NextPage } from 'next';

interface PageProps {
  params: Record<string, string>;
  searchParams: {
    location?: string;
  };
}

const SellYourCar: NextPage<PageProps> = ({ params, searchParams }) => {
  // Extract location from search params (passed through rewrites)
  const location: string = searchParams.location || 'your area';

  return (
    <div className="container mx-auto py-8">
      <h1 className="text-3xl font-bold mb-6">Sell Your Car in {location}</h1>

      <section className="mb-8">
        <h2 className="text-2xl font-semibold mb-4">Why Sell Your Car With Us in {location}?</h2>
        <p>
          We offer the best prices for your used car in {location}. Our network of buyers 
          ensures you get competitive offers quickly and hassle-free.
        </p>
      </section>

      <section>
        <h2 className="text-2xl font-semibold mb-4">How It Works in {location}</h2>
        <ol className="list-decimal pl-5">
          <li className="mb-2">Fill out our simple online form with your car details</li>
          <li className="mb-2">Receive instant estimated value for your car</li>
          <li className="mb-2">Schedule an inspection at our {location} center</li>
          <li className="mb-2">Get paid on the spot after inspection approval</li>
        </ol>
      </section>
    </div>
  );
};

export default SellYourCar;

Step 2: Configure Rewrites in next.config.js

Next, I set up the rewrites in my next.config.js file:

// next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
  async rewrites() {
    return [
      {
        source: '/sell-your-car-in-:location',
        destination: '/sell-your-car?location=:location',
      },
    ];
  },
};

module.exports = nextConfig;

Conclusion

This simple yet powerful implementation solves our routing challenge elegantly. With just two files, we've created a system that can handle an unlimited number of location-based URLs without creating separate pages for each one.

The key benefits of this approach include:

  1. DRY Code: One component serves multiple URLs, reducing duplication

  2. Maintainability: Updates to the page structure only need to be made in one place

  3. SEO-Friendly: Each URL preserves its unique path for search engines

  4. Performance: Only one page component needs to be loaded and cached

  5. Scalability: Adding new locations doesn't require code changes

Next.js 15's rewrites feature provides the perfect solution for handling dynamic, parameter-based URLs while maintaining clean code architecture. This pattern can be applied to many other scenarios beyond location-based content – product categories, service areas, or any situation where you need similar content with different parameters.

By leveraging TypeScript, we also gain the benefits of type safety and better developer experience, making our implementation both robust and maintainable.

The best part? It's incredibly simple to implement, requiring minimal code changes to achieve powerful URL handling capabilities.