If you’ve ever had to secure a Next.js app, you already know how confusing it can get. JWTs, OAuth, NextAuth, middleware, it’s a lot to juggle. I’ve made all the rookie mistakes, from exposing sensitive tokens to mixing up client vs. server logic. But after a few deep dives and late-night debugging sessions, I’ve landed on a setup that actually works and keeps things secure.

Let me walk you through it.

1. Choosing the Right Auth Strategy

JWT vs. OAuth vs. NextAuth.js

  • JWT (JSON Web Tokens): Great for APIs and mobile apps. But be careful with token storage, never store JWTs in localStorage.
  • OAuth (Google, GitHub logins): Best used with a wrapper like NextAuth.
  • NextAuth.js: My go-to now. Handles both authentication and session management with minimal config.

2. Using Middleware for Authorization

Next.js middleware is perfect for securing routes at the edge. I use it to check sessions before rendering a page:

// middleware.ts

import { getToken } from "next-auth/jwt";

import { NextResponse } from "next/server";

 

export async function middleware(req) {

  const token = await getToken({ req, secret: process.env.JWT_SECRET });

  const isAuthPage = req.nextUrl.pathname.startsWith("/login");

 

  if (!token && !isAuthPage) {

    return NextResponse.redirect(new URL("/login", req.url));

  }

 

  return NextResponse.next();

}

Why this is awesome:

  • Runs on the edge = faster redirects.
  • Protects routes without cluttering your pages.

3. Securing JWTs and Sessions

Mistake I made: storing JWTs in localStorage. Huge no-no because of XSS attacks.

Better Way:

  • Use HTTP-only cookies via NextAuth.js.
  • Enable secure, sameSite, and httpOnly flags.

In NextAuth:

callbacks: {

  async session({ session, token }) {

    session.user.id = token.id;

    return session;

  },

}

4. Role-Based Access Control (RBAC)

Once I had multiple user types (admins, editors, guests), I needed fine-grained access.

My approach:

  • Add role in JWT or session object.
  • Use server-side checks or middleware to gate content:
if (session.user.role !== "admin") {

  return NextResponse.redirect("/unauthorized");

}

5. Client-Side Protection

Don’t forget to gate things client-side too. I use:

if (!session) return <Loader />;

if (session.user.role !== "admin") return <Error />;

But always remember: never trust the client fully. Server/middleware is your real bouncer.

Final Words

Security in Next.js isn’t hard, it just needs structure. Once I separated concerns (auth, role-checks, secure storage), it all clicked.

Whether you’re using JWT, OAuth, or NextAuth, just remember to keep tokens safe, use middleware for smart gating, and test your flows.

Our Trusted
Partner.

Unlock Valuable Cloud and Technology Credits

Imagine reducing your operational costs by up to $100,000 annually without compromising on the technology you rely on. Through our partnerships with leading cloud and technology providers like AWS (Amazon Web Services), Google Cloud Platform (GCP), Microsoft Azure, and Nvidia Inception, we can help you secure up to $25,000 in credits over two years (subject to approval).

These credits can cover essential server fees and offer additional perks, such as:

  • Google Workspace accounts
  • Microsoft accounts
  • Stripe processing fee waivers up to $25,000
  • And many other valuable benefits

Why Choose Our Partnership?

By leveraging these credits, you can significantly optimize your operational expenses. Whether you're a startup or a growing business, the savings from these partnerships ranging from $5,000 to $100,000 annually can make a huge difference in scaling your business efficiently.

The approval process requires company registration and meeting specific requirements, but we provide full support to guide you through every step. Start saving on your cloud infrastructure today and unlock the full potential of your business.

exclusive-partnersexclusive-partners

Let's TALK

Let's TALK and bring your ideas to life! Our experienced team is dedicated to helping your business grow and thrive. Reach out today for personalized support or request your free quote to kickstart your journey to success.

DIGITAL PRODUCTUI/UX DESIGNDIGITAL STUDIOBRANDING DESIGNUI/UX DESIGNEMAIL MARKETINGBRANDING DESIGNUI/UX DESIGNEMAIL MARKETING
DIGITAL PRODUCTUI/UX DESIGNDIGITAL STUDIOBRANDING DESIGNUI/UX DESIGNEMAIL MARKETINGBRANDING DESIGNUI/UX DESIGNEMAIL MARKETING