Understanding Dynamic Routing and API Routes in Next.js

Instead of creating files for all pages, next.js is a JavaScript-based React framework that allows you to create different routes and work with the query data to dynamically create pages. That’s the phenomenon of dynamic routing in next.js.

Instead of creating files for all pages, next.js is a JavaScript-based React framework that allows you to create different routes and work with the query data to dynamically create pages. That’s the phenomenon of dynamic routing in next.js.

Next.js serves dynamic content based on a dynamic URL that is created within the brackets [] syntax. What happens is that you create a folder and place a file with open and closing brackets within its name. It will then route all the requests to the internal file hence substituting the value inside the brackets whenever needed.

For example: /pages/profile/[username].js

This folder structure will handle all the dynamic URLs under the /profile/ route. [username].js means that any dynamic property which is our username, in this case, is put inside the [username].js parameter of the query property of the router.

I know that’s pretty complicated stuff. But just hold on and let me first explain what’s a Next.js router.

Router in Next.js

The router is one of the libraries in next.js which can be imported via the following command:

import { useRouter } from 'next/router'

This means that whenever you need to access the router object inside any function component in your next.js app, you do it via using the useRouter hook. Once this is done, you start the router object via:

const router = useRouter();

Understanding Dynamic Routing and API Routes

To understand how dynamic routing works in Next.js let’s quickly do a brief user example.

It creates a folder hierarchy as shown above. Next, create a new folder called profile inside the pages directory. And finally a [username].js file inside the profile folder. This creates the folder structure as:

The idea behind this is simple. I want to display different usernames whose values can be changed dynamically.

Let’s now apply the console.log (router); function study its contents:

The results tell that username resides inside the query and to access the results dynamically replace the [username].js file with the following code:

This time we’ve defined const{ username }= router.query; which dynamically accesses the query part of the router object and gets displayed at the front-end.

The above implementation is one of the most basic depiction of how dynamic routing works in Next.js. In my next article, I am going to put it into a more useful example where I’ll explain how to fetch data from a remote API say my WordPress blog posts. Till then try these basics and let me know your feedback.