Basic Routing and Pages in Next.js
Tags: nextjs, fullstack, javascript, typescript
Published: 2024-05-08 14:32:20

_This article originally appeared on my [blog](https://jaydevm.hashnode.dev/bite-sized-nextjs-part-3-basic-routing-and-pages)._

Hey there! In the last couple lessons we covered [what Next.js is](https://jaydevm.hashnode.dev/nextjs-essentials-part-1-introduction) and how to [set up your first project](https://jaydevm.hashnode.dev/nextjs-essentials-part-2-installation-and-setup). If you have read those guides, you are ready to learn about pages and routing. Fortunately, making routes and pages in Next.js is a snap to understand!

Let’s take a look at how routing works first.

## Creating Routes and Pages

### Routes

Creating your client-side pages in Next.js is wonderfully straightforward, thanks to its file-based routing system. You just need to know two concepts:

1. Your source code directory paths become your URL structure. For example, a file at `app/dashboard/settings/page.tsx` will appear in your browser at `http://myserver/dashboard/settings`.
    
2. To make a URL accessible in your app, you must use a file named `page` within the appropriate directory. This file can end with `.js`, `.ts`, `.jsx`, or `.tsx`.
    

You can see this paradigm in action when you set up a new Next.js app. The screenshot below shows the index URL `localhost:3000` is controlled by the index page `app/page.tsx`.

![next.js starter index page](https://cdn.hashnode.com/res/hashnode/image/upload/v1715178179236/def51769-e048-49b9-b64c-0d5659de30a4.png)

As you might have guessed, you can nest these folders as deeply as you would like.

Here’s an example of a folder hierarchy that’s a few levels deep:

![nested next.js folder hierarchy](https://cdn.hashnode.com/res/hashnode/image/upload/v1715178206464/a01b9ef7-f62d-4e7e-a7d6-ed9161110d88.png)

And here’s the corresponding browser page. The URL matches our folders above.

![next.js app nested url path](https://cdn.hashnode.com/res/hashnode/image/upload/v1715178216893/ae29acac-577f-4b24-994e-e76cea83bc9e.png)

### Pages

Once you have your route paths established, creating your page is as simple as exporting a React component from a `page.jsx` or `page.tsx` file:

```typescript
export default function Page() {
  return <h1>Hello, Dashboard Page!</h1>
}
```

## Using Dynamic Segments

Dynamic segments allow you to capture variable segments from the URL. Create a folder somewhere in your directory path with brackets around its name to accept dynamic parts.

For example, `app/settings/[username]/page.tsx` will yield a route that accepts any value for `username` and incorporates it as an input parameter into the page’s component:

```typescript
export default function Page({ params }: { params: { username: string } }) {
  return <div>This is the settings page for {params.username}</div>
}
```

## Linking and Navigating

You now understand the basic components of a Next.js app. How do you connect routes and pages together?

### Basic Example

Next.js utilizes the `Link` component from `next/link` to enable client-side navigation between pages, ensuring that the transitions are quick and do not require a page reload. Here’s how you can link to the About page from, say, the homepage:

```xml
import Link from 'next/link';

const Home: React.FC = () => {
  return (
    <div>
      Visit the <Link href="/about"><a>About Page</a></Link>.
    </div>
  );
}

export default Home;
```

### Dynamic Segments

As a full-stack framework built on React, Next.js has full React support. Thus you can use all of the niceties of React, such as template literals and string interpolation, when coding for dynamic links.

```typescript
// app/zoo/animals.jsx

import Link from 'next/link'
 
export default function ZooAnimals({ animals }) {
  return (
    <ul>
      {animals.map((animal) => (
        <li key={animal.id}>
          <Link href={`/blog/${animal.species}`}>{animal.name}</Link>
        </li>
      ))}
    </ul>
  )
}
```

### Programmatic Routing

You can use Next’s built-in router to programmatically change pages (i.e. without user interaction). This can be especially useful in scenarios where you need to redirect a user after an action such as form submission or login.

Note that this is only available in client components, so you need to declare `'use client'` at the top of the file.

```typescript
'use client'

import { useState } from 'react';
import { useRouter } from 'next/navigation';

export default function LoginForm({ username }: { username: string }) {
  const router = useRouter();

  const handleLogin = async (event: React.FormEvent) => {
      event.preventDefault();
      
      // Simulating a login process - replace with actual logic
      const loginSuccessful = true;
      
      if (loginSuccessful) {
          router.push(`/profile/${username}`);
      } else {
          alert('Login failed!');
      }
  };
  
  return (
     <form onSubmit={handleLogin}>
       <button type="submit">Login</button>
     </form>
  );
};
```

## Conclusion

And there you have it — a thorough dive into the basics of pages and routing in Next.js! By now, you should feel comfortable creating static and dynamic routes, linking between pages seamlessly, and even navigating programmatically within your applications. These foundational skills are crucial to your understanding of Next.js.

In our next lesson, we'll push the boundaries further as we learn advanced page and routing techniques. Make sure to [subscribe](https://jaydevm.hashnode.dev/newsletter) if you want to catch the next chapter as soon as it drops!