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.
-
SessionProvider
Contains 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.js
since it's provided bygetServerSideProps(context)
onprofile.js
.auth.js
will 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.js
component. -
getSession()
Backend - Used to protect the API Route. -
CredentialsProvider
Manages token creation behind the scenes,JWT
(JSON Web Token), used in/api/auth/[...nextauth]
. Needs to be a 'catch all route' becausenext-auth
exposes multiple routes for login, logout and others more.List of
next-auth
exposed 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.js
page, since it needs to verify if the user is authorized. It also redirects the user fromprofile.js
toauth.js
if the user is not authorized, thus keepingprofile.js
only 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
-
bcryptjs
used for hashing and comparing passwords. -
MongoClient
for database connection.
-
POST
to send login data. -
PATCH
to 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-auth
project 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');
}