Require user authentication and redirect to originally requested page

During this episode, we focus on requiring the user to login before creating a new project.

Using Next.js and NextAuth.js we redirect the user if they have no session and then return them back to the New Project page on successful login.

This project was initially set up using the T3 stack.

On the page where you require a user to be authenticated check the user session using getServerSession from next auth.

export const getServerSideProps: GetServerSideProps = async (context) => { const temporaryUserId = setTemporaryUserIdCookie(context) const session = await getServerSession(context.req, context.res, authOptions) if (!session) { return { redirect: { destination: '/users/login?redirect=/projects/new', permanent: false, }, } } return { props: { temporaryUserId } } }

On the login page grab the redirect query string and use it as the callback url:

import { useRouter } from 'next/router' import { Button, Flex, Heading, VStack, } from '@chakra-ui/react' import { signIn } from 'next-auth/react' import { SiAuth0, SiFacebook } from 'react-icons/si' import MobileLayout from '@layouts/MobileLayout' const CALLBACK_URL = '/users/account' const UserLoginPage = () => { const routerPayload = useRouter() const { query } = routerPayload const callbackUrl = query?.redirect || CALLBACK_URL return ( <MobileLayout> <Flex direction="column" marginTop={8}> <Heading fontWeight="medium" size="lg"> Login or Sign Up </Heading> <VStack alignItems="flex-start" marginTop={8}> <Button leftIcon={<SiFacebook />} onClick={() => signIn('facebook', { callbackUrl })} width="100%" > Login with Facebook </Button> <Button leftIcon={<SiAuth0 />} onClick={() => signIn('auth0', { callbackUrl })} width="100%" > Login with Auth0 </Button> </VStack> </Flex> </MobileLayout> ) } export default UserLoginPage
View More Posts

Portfolio built using the open source project by

Initium Studio

Create your own Next.js Portfolio with Contentful CMS by forking this repo onGitHub












2024 Greeff Consulting Pty Ltd