Next.js Discord

Discord Forum

How create Custom URLs in Next.js with Next.js Router?

Unanswered
ivanm0067 posted this in #help-forum
Open in Discord
I am working on a Next.js application with an app directory structure. In my application, I have a page called itemDetail that displays the details of a specific item. However, I want to customize the URL so that it looks like /items?search=[id] instead of the default /itemDetail/[id].

I have tried using Next.js Router's rewrites() function in my next.config.js as follows:

// next.config.js

module.exports = { async rewrites() { return [ { source: '/items?search=:id', destination: '/itemDetail/:id', }, ]; }, };

In my itemList page, I am using the following link to navigate to the itemDetail page:

// itemList.tsx import Link from 'next/link'; // Inside the component <Link href={/items?search=${item.id}} >{item.title}</Link>


Structure app:
app
├── itemDetail
│ ├── [id]
│ │ └── page.tsx
├── ItemList
│ └── page.tsx
├── layout.tsx
└── page.tsx

Expected Result:

I expected that when I access the custom URL /items?search=[id], it would properly redirect to the itemDetail page with the corresponding item ID. However, the redirection didn't work as expected, and I encountered issues with the custom URL pattern.

I'm following the Next documentation but I couldn't find any solution to my code

I would appreciate any help, guidance, or suggestions on how to correctly implement this custom URL pattern using Next.js Router in my app directory structure. Thank you!

2 Replies

try this instead
{
  source: '/items',
  has: [
    {
      type: 'query', 
      key: 'search',
      value: '(?<search>.*)'
    }
  ],
  destination: '/itemDetail/:search',
},
I remove the [id] folder and I move the page.tsx inside into itemDetail and is working!