skip to Main Content

for my blog app in NextJS I’m trying to create a route for usernames. If a user navigates to /@${username} I want to display the page in /pages//index.tsx. That works but if I randomly navigate to /abc it displays that page (with an error, obviously) and not the default 404 page

2

Answers


  1. I’m blind-flying on this right now as I don’t have Next.js and/or Node installed on my current machine, but is it an idea to create a redirect from /@${username} to /${username}?

    If that could work for you, try adding the following to your next.config.js:

    // next.config.js
    
    module.exports = {
      // Other configuration options
      async redirects() {
        return [
          {
            source: '/@:username*',
            destination: '/user/:username*',
            permanent: true,
          },
        ];
      },
    };
    

    With this configuration, when a user navigates to /@[username], it will redirect to /user/[username], which will be handled by the dynamic route file at pages/user/[username].tsx.

    Login or Signup to reply.
  2. One way to implement the desired behavior is with getServerSideProps:

    import type { GetServerSideProps } from "next";
    
    type UserPageProps = {
      user: string;
    };
    
    export const getServerSideProps: GetServerSideProps<UserPageProps> = async ({
      params,
    }) => {
      if (params && params.username) {
        const username = Array.isArray(params.username)
          ? params.username[0]
          : params.username;
        if (username.at(0) === "@") {
          return { props: { user: username.substring(1) } };
        }
      }
      return { notFound: true };
    };
    
    export default function UserPage({ user }: UserPageProps) {
      return <>Hello, {user}</>;
    }
    
    

    Another option would be to use router on the client and check the router.query.username after hydration.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search