Nextjs routing to username slug url e.g (site.com/username)

Viewed 30

So what I'm trying to achieve is a username page, for example, if a username is Jack then site.com/jack

My folder structure looks like this pages > [user] > index.js but because of this if there's a typo or someone goes to a page that doesn't exist (site.com/abc) the user page will be displayed.

This is what my code looks like, obviously, it is throwing an error because this is incomplete. I can't figure out how can I get the username

import React from "react";


export const getServerSideProps = async (context) => {
  const { user } = context.query;
return {
props: {
user
}}}


export default function Header() {

  return (
    <div>
      index
    </div>
  )
 }
1 Answers

You can check to see if there is a user with that specific name, if not you can redirect to the 404 page.

export async function getServerSideProps(context) {
    const { user } = context.query;
    if (!user) {
     return {
      redirect: {
        destination: '/404',
        permanent: false,
      },
    }
  return {
    props: {user}, // will be passed to the page component as props
  }
  }

}
Related