New product features | The latest in technology | The weekly debugging nightmares & more!
July 25, 2023
Take my knowledge and shove it up your brain...
Using Auth.js is one of the most popular ways to protect your application, and the reason is that it comes with so many features like passwordless login and it supports most of the well-known providers.
And it's very simple to add authentication to your routes handlers using auth.js.
route.ts
1import { getServerSession } from "next-auth/next"
2import { authOptions } from "./auth/[...nextauth]"
3
4export default async (req, res) => {
5 const session = await getServerSession(req, res, authOptions)
6 if (session) {
7 // Signed in
8 console.log("Session", JSON.stringify(session, null, 2))
9 } else {
10 // Not Signed in
11 res.status(401)
12 }
13 res.end()
14}
The above code is simple all you need to protect a route handler.
If there's a user, return some data, if there isn't throw an error.
You can find more examples in their documentation
How to add credential authentication using Auth.js & Next 14
Allow users to login using their email & password.
How to add email verification using Auth.js
Enhance your website security by allowing only verified users to log in.
How to enable password reset using auth.js
Forgot your password? now worries, I got your bro.
How to add 2-factor authentication
Enhance your users' security using 2-factor authentication