1 | initial version |
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.