Create Next.js Middleware for Authentication and Redirects

Use this AI prompt to generate a middleware file for Next.js App Router that checks authentication tokens, handles redirects, and protects routes efficiently.

🧠 What This Prompt Does

This AI prompt generates a Next.js middleware for handling authentication, redirect logic, and route protection.
It’s ideal for apps that need lightweight security before hitting server routes or rendering protected pages.


💬 The Prompt

You are a Next.js developer.
Generate a middleware.ts file that:

- Checks authentication status via cookies or headers
- Redirects unauthenticated users to /login
- Allows access to public routes like /, /about, /contact
- Works with Next.js App Router

🚀 Example Output (AI Generated)

import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

const PUBLIC_ROUTES = ['/', '/login', '/about'];

export function middleware(req: NextRequest) {
  const token = req.cookies.get('token')?.value;

  if (!token && !PUBLIC_ROUTES.includes(req.nextUrl.pathname)) {
    const loginUrl = new URL('/login', req.url);
    return NextResponse.redirect(loginUrl);
  }

  return NextResponse.next();
}

export const config = {
  matcher: ['/((?!_next|api|static|favicon.ico).*)'],
};

📘 When to Use This Prompt

  • To restrict access to protected routes in Next.js.
  • When adding lightweight authentication middleware.
  • To enforce route-based access control without server bloat.

💡 Best Practices

  • Keep public routes explicitly listed for clarity.
  • Use JWT or cookies for session management.
  • Avoid heavy logic inside middleware (it runs on every request).
  • Cache static assets to reduce performance impact.

🏁 Summary

This prompt helps you create a secure, efficient middleware for authentication and redirects in Next.js.
It ensures only authorized users access protected content while keeping routing clean and fast.

Frequently Asked Questions

Where should I place the middleware file?

Place it at the project root or inside the app directory where you want route protection. It must be named `middleware.ts`.

Can I check cookies or JWT tokens in middleware?

Yes, Next.js allows accessing request headers and cookies directly inside middleware for lightweight auth checks.

Does middleware run before API routes?

Yes, middleware executes before both page and API route handlers, allowing global request filtering.

nextjsmiddlewareauthredirectsai-prompt

Advertisement