Nextjs - first level dynamic route

Viewed 944

I want to have user profiles in my app at domain.com/:username .How do I do it? creating a new folder in /pages will create a new URL section like /user/:username which I don't want.

2 Answers

Just name your file inside pages as [username].js

Creating a dynamic route

You can create a dynamic route by putting the filename in brackets. For instance:

  • pages/[id].js
  • pages/[slug].js
  • pages/posts/[slug].js
  • pages/[author]/[slug].js
  • pages/[author]/bio.js

Notice how the dynamic route can be at any level. It doesn't simply need to be at the root of the pages folder, and it doesn't need to be the last level of the url either. Also notice that you can name the dynamic route anything you want. You're not restricted to just using [id] or [slug].

In your case, use pages/[username].js

Accessing the route name

If you create a dynamic route at pages/posts/[slug].js, any page at https://example.com/posts/slug-of-the-post will lead to that page. However, you likely want different content on each page (i.e., that the user is on https://example.com/posts/slug-of-the-post, not https://example.com/posts/slug-of-a-different-post. For this, you need to access the contents of the route.

Inside the page

You can use the router to get the name of the route.

// pages/posts/[slug].js

import { router } from 'next/router'

export default function PostPage() {
  const router = useRouter()
  
  const slug = router.query.slug // "slug" because that was the name of the file

  return <>{/* page contents */} </>
}

So on page https://example.com/posts/slug-of-the-post, the variable slug will be slug-of-the-post.

If you used [id].js, use router.query.id instead.

GetStaticProps/GetServerSideProps

Using the server-side functions, the process is very similar.

// pages/posts/[slug].js

// bottom of the file

export async function getServerSideProps(context) {
  const slug = context.params.slug

  return {
    props: {},
  }
}

Docs

By the way, I'd also recommend checking out the docs if you haven't already:

https://nextjs.org/docs/routing/dynamic-routes

Related