Nader's Daily Blog
Welcome to Every Developers favorite blog in the Devosphere

New product features | The latest in technology | The weekly debugging nightmares & more!

Using Auth.js (next auth) to protect route handlers

Using Auth.js (next auth) to protect route handlers

July 25, 2023

Nader Elmahdy

Nader Elmahdy

Take my knowledge and shove it up your brain...

So many ways to protect your route handlers, today it's about auth.js

Authentication

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

You might also like: