Live at: https://nextjs-authentication-eight.vercel.app/
This is a Next.js project bootstrapped with create-next-app.
Project built using next-auth library to handle authentication.
-
SessionProviderContains the 'session context' and is exposed at the top level of the application_app.js.<SessionProvider session={pageProps.session}>This will skip the 'session http request' onprofile.jssince it's provided bygetServerSideProps(context)onprofile.js.auth.jswill send this 'session http request' since it does not have agetServerSideProps(context). -
useSession()Frontend - Add React Hook. Checks if someone is signed in. Used inmain-navigation.jscomponent. -
getSession()Backend - Used to protect the API Route. -
CredentialsProviderManages token creation behind the scenes,JWT(JSON Web Token), used in/api/auth/[...nextauth]. Needs to be a 'catch all route' becausenext-authexposes multiple routes for login, logout and others more.List of
next-authexposed routes (that should not be overwritten by your custom ones): https://next-auth.js.org/getting-started/rest-api. Other providers overview: https://next-auth.js.org/providers/
-
getServerSideProps()fetches data from server on each request. Needed forprofile.jspage, since it needs to verify if the user is authorized. It also redirects the user fromprofile.jstoauth.jsif the user is not authorized, thus keepingprofile.jsonly visible to authorized users. -
useRouter()for redirects. (e.g.: after login/logoutrouter.replace('/')).
-
useRef()for capturing input in forms (e.g.: e-mail, password, etc.) -
useState()for setting and using state (e.g.: loading, error messages, request status like 'pending/success/error') -
useEffect()for setting timeout (e.g.: notification); check for session/authenticationauth.js
-
bcryptjsused for hashing and comparing passwords. -
MongoClientfor database connection.
-
POSTto send login data. -
PATCHto change password.
getStaticProps()could be implemented for additional content like a list of products andgetStaticPaths()for accounting for dynamic pages with e.g. PDP (product detail pages). This would be outside of the scope of thisnext-authproject though.
Setting an <input /> type from "password" to "text" shows the typed in password.
Only redirects after reloading the page or explicitly typing the URL. Thus the need to define the redirect in the component to redirect it automatically after login.
getServerSideProps() example! on auth.js page, in an attempt to redirect to profile.js page after logging in. Doesn't work.
if (session) {
return {
redirect: {
destination: '/profile',
permanent: false,
},
};
}auth-form component does the job.
if (!result.error) {
setRequestStatus('success');
router.replace('/profile');
}