'How to route to page using Dynamic Routes in next.js

I am trying to route these urls to [id].js file in next.js, So everything is working for url 2 and 3 below, but its not working for url 1 so I have to create another index.js file which I dont want. Is is possible to use the same [id].js file? for url 1 also.

url 1 -> /settings
url 2 -> /settings/notifications
url 3 -> /settings/security

my file structure

settings > [id].js

getting the id

const router = useRouter()
const { id } = router.query;


Solution 1:[1]

A file structure like the below is one way to do it:

settings 
    > [id]
    > index

But if you do not want to add an index file you can make use of optional catch-all routes feature. Please note that it comes with other features you might not want and this might change your code a little too.

This is the structure you will have to follow:

settings
    >[[...id]]
{ } // GET `/post` (empty object)
{ "slug": ["notifications"] } // `GET /settings/notifications ` (single-element array)
{ "slug": ["notifications", "security"] } // `GET /settings/notifications/security ` (multi-element array)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tushar Shahi