Next.js Intercepting Routes 101

·

1 min read

Next.js Intercepting Routes 101

Recently, I was working on a side project where I encountered a problem that piqued my interest.

I wanted to create a modal with the same content as the authentication page without opening the page itself and displaying it inside the home page when I clicked on the sign-in button.

This is where I came across Intercepting Routes in Next.js 14.

In short, it does what I wanted it to do. It helps you display specific content that is normally under a different route, and when you refresh, it takes you to the route of the displayed content and loads its page.

The syntax may seem a bit strange, but it is as follows (the example I will explain is in the images):

Create a folder prefixed with @, which we call a slot. Like dynamic routes, the slot does not appear in the params.

Here, to display the content of the page under the sign-in route, I create a folder prefixed with (.) and named the route with the same name as the targeted route. Under the folder, you create your UI as usual and call the same functionality to perform the same task.

Finally, you create a default file to act as a fallback if the route does not exist or if an error occurs.