Conversational Thread with Reactions

Conversation

Yesterday
JD
You2:30 PM
What's the best way to handle authentication in a Next.js app?
AI
Atlas AI2:30 PM

For Next.js authentication, I recommend using NextAuth.js (now called Auth.js). It provides:

  • Built-in providers for Google, GitHub, and 50+ OAuth services
  • Session management with JWT or database sessions
  • Middleware-based route protection
  • TypeScript support out of the box

For a simpler alternative, Better Auth is gaining popularity with its straightforward API and built-in email/password support.

Today
JD
You10:15 AM
How do I protect API routes with NextAuth?
AI
Atlas AI10:15 AM

You can protect API routes using the getServerSession helper:

  • Import getServerSession from next-auth
  • Call it at the top of your API handler
  • Check if the session exists, return 401 if not

For App Router, use the auth() helper from your NextAuth config. It works in Server Components, Route Handlers, and Middleware.

For middleware-based protection, create a middleware.ts file and use the withAuth wrapper to protect entire route patterns.

JD
You10:16 AM
Can you show the middleware approach?
AI
Atlas AI10:17 AM

The middleware approach is clean and centralized. Create a middleware.ts in your project root:

Use withAuth from next-auth/middleware and export a config object with a matcher array to specify which routes to protect. For example, matcher: ["/dashboard/:path*", "/api/protected/:path*"].

This automatically redirects unauthenticated users to the sign-in page. You can also add custom logic in the authorized callback to check for specific roles or permissions.

About this block

Conversational Thread with ReactionsPRO

Chat message thread with rich formatting, copy and thumbs-up/down action buttons on AI messages, and time-grouped message sections. Features hover-revealed action bars and smooth animations.

More Chat blocks

View all Chat
PRO

chat22

Member Inbox And Thread

PRO

chat11

Complete AI Chat Interface

PRO

chat23

Messaging Overview Split

Get Pro access