- Home
- Services
- IVY
- Portfolio
- Blogs
- About Us
- Contact Us
- Sun-Tue (9:00 am-7.00 pm)
- infoaploxn@gmail.com
- +91 656 786 53
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.
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(); }
Mistake I made: storing JWTs in localStorage. Huge no-no because of XSS attacks.
Better Way:
In NextAuth:
callbacks: { async session({ session, token }) { session.user.id = token.id; return session; }, }
Once I had multiple user types (admins, editors, guests), I needed fine-grained access.
if (session.user.role !== "admin") { return NextResponse.redirect("/unauthorized"); }
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.
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.
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:
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.