Ask Your Question
2

What is the method for creating secured routes in NextJS 13?

asked 2023-05-06 12:07:19 +0000

plato gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2023-05-06 12:13:02 +0000

devzero gravatar image

In NextJS 13, you can create secured routes using the built-in getServerSideProps function in conjunction with the getSession function provided by the next-auth library. Here are the steps:

Step 1: Install and configure next-auth in your NextJS app.

Step 2: Create a custom function to check if a user is authenticated. This function will use getSession from next-auth to check if the user has an active session.

import { getSession } from 'next-auth/client'

export const isUserAuthenticated = async (context) => {
  const session = await getSession(context)

  if (!session) {
    return {
      redirect: {
        destination: '/login',
        permanent: false,
      },
    }
  }

  return {
    props: {},
  }
}

Step 3: In your page component, use getServerSideProps to call the isUserAuthenticated function.

import { isUserAuthenticated } from '../utils/auth'

export const getServerSideProps = async (context) => {
  const auth = await isUserAuthenticated(context)

  return auth
}

const MySecuredPage = () => {
  // your secured page content here
}

export default MySecuredPage

Step 4: Make sure to include the user's session in your page's initial props so you can access the user's information.

export const getServerSideProps = async (context) => {
  const auth = await isUserAuthenticated(context)

  const session = await getSession(context)

  return {
    ...auth,
    props: {
      session,
    },
  }
}

That's it! Now your page is secured and will only be accessible to users that are authenticated.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-05-06 12:07:19 +0000

Seen: 15 times

Last updated: May 06 '23