Next.js Discord

Discord Forum

check if user is authenticated in route handlers

Answered
Silver Fox posted this in #help-forum
Open in Discord
Silver FoxOP
Hi, How do I check if the user sending the request is authenticated?
import { auth } from "@/auth";
import { db } from "@/lib/db";

export async function POST(
  request: Request
) {
  console.log(request)
  const body = await request.json()
  const { postId } = body
  const session = await auth()
  if (!postId || typeof postId !== 'string') {
    return Response.json({ error: "Invalid request body" }, { status: 500 })
  }

  try {
    const result = await db.text.findUnique({
      where: {
        id: postId
      }
    })

    return Response.json({ result })
  }
  catch (error) {
    console.log(error)
    return Response.json({ error: "Something went wrong!" }, { status: 500 })
  }
}


Or do I use middleware?
Answered by Silver Fox
const { auth } = NextAuth(authConfig)

export default auth((req) => {
  const { nextUrl } = req
  const isLoggedIn = !!req.auth
...
  if (!isLoggedIn && !isPublicRoute) {
    let callbackUrl = nextUrl.pathname
    if (nextUrl.search) {
      callbackUrl += nextUrl.search
    }
    const encodedCallbackUrl = encodeURIComponent(callbackUrl)
    return Response.redirect(new URL(`/auth/login?callbackUrl=${encodedCallbackUrl}`, nextUrl))
  }
...

using this in middleware works
View full answer

2 Replies

Komondor
Check the session object you have. I'd use middleware
Silver FoxOP
const { auth } = NextAuth(authConfig)

export default auth((req) => {
  const { nextUrl } = req
  const isLoggedIn = !!req.auth
...
  if (!isLoggedIn && !isPublicRoute) {
    let callbackUrl = nextUrl.pathname
    if (nextUrl.search) {
      callbackUrl += nextUrl.search
    }
    const encodedCallbackUrl = encodeURIComponent(callbackUrl)
    return Response.redirect(new URL(`/auth/login?callbackUrl=${encodedCallbackUrl}`, nextUrl))
  }
...

using this in middleware works
Answer