DeployU
Interviews / Frontend Engineering / How do you do routing in Next.js?

How do you do routing in Next.js?

practical Routing Interactive Quiz Code Examples

The Scenario

You are a frontend engineer at a social media company. You are building a new application that will have multiple pages, such as a home page, a profile page, and a settings page.

You need to find a way to handle the routing between these pages.

The Challenge

Explain how you would do routing in Next.js. What is the file-system based router, and what are the key features of it?

Wrong Approach

A junior engineer might try to solve this problem by using a library like React Router. This would work, but it would not be the standard way to do routing in Next.js.

Right Approach

A senior engineer would know that Next.js has a built-in file-system based router. They would be able to explain how it works and how to use it to handle the routing between the different pages.

Step 1: Understand What the File-System Based Router Is

Next.js has a file-system based router. This means that you can create a new route by just creating a new file in the pages directory.

Step 2: The Key Features of the File-System Based Router

FeatureDescription
Index RoutesThe file pages/index.js is mapped to the / route.
Nested RoutesThe file pages/about/us.js is mapped to the /about/us route.
Dynamic RoutesThe file pages/posts/[id].js is mapped to the /posts/:id route.

Step 3: Code Examples

Here are some code examples that show how to create different types of routes:

Index Route:

// pages/index.js
export default function Home() {
  return <h1>Home Page</h1>;
}

Nested Route:

// pages/about/us.js
export default function AboutUs() {
  return <h1>About Us Page</h1>;
}

Dynamic Route:

// pages/posts/[id].js
import { useRouter } from 'next/router';

export default function Post() {
  const router = useRouter();
  const { id } = router.query;

  return <h1>Post: {id}</h1>;
}

You can use the Link component from next/link to navigate between routes.

import Link from 'next/link';

export default function Home() {
  return (
    <div>
      <Link href="/about/us">
        <a>About Us</a>
      </Link>
    </div>
  );
}

Practice Question

You want to create a new route for `/products/123`. Which of the following would you use?