auth-next
v1.0.4
Published
A reusable Next.js middleware package
Readme
auth-next
A simple and reusable Next.js middleware for authentication. This package provides a pre-built middleware function that you can easily integrate into your Next.js projects to protect your routes.
Installation
npm install auth-next
Usage
Create middleware.ts in your Next.js project's src directory (or root if you aren't using src):
// middleware.ts import { createMiddleware } from "nextjs-auth-middleware"; import { NextRequest, NextResponse } from 'next/server';
const { middleware, config } = createMiddleware({ publicRoutes: ["/home"], // Routes that don't require authentication authAppUrl: process.env.AUTH_APP_URL, // URL of your authentication application callbackUrl: process.env.CALLBACK_URL, // URL to redirect to after authentication });
export { middleware, config };
Set up environment variables:
Make sure to set the AUTH_APP_URL and CALLBACK_URL environment variables in your Next.js project's .env file or deployment environment.
AUTH_APP_URL=https://your-auth-app.com CALLBACK_URL=https://your-app.com/protected-route
Configuration Options
The createMiddleware function accepts an options object with the following properties:
publicRoutes: string[] (Optional) - An array of routes that don't require authentication. Defaults to ["/home"].
authAppUrl: string (Optional) - The URL of your authentication application. This URL will be used to redirect users who are not authenticated. Defaults to process.env.AUTH_APP_URL or an empty string if the environment variable is not set.
callbackUrl: string (Optional) - The URL to redirect to after successful authentication. Defaults to process.env.CALLBACK_URL or an empty string if the environment variable is not set.
matcher: string[] (Optional) - An array of route patterns that the middleware should apply to. Defaults to ["/:path*"] (all routes). This uses Next.js's matcher syntax.
Examples Custom Matcher
To override the default matcher, provide a matcher array in the options object:
// middleware.ts import { createMiddleware } from "nextjs-auth-middleware";
const { middleware, config } = createMiddleware({ publicRoutes: ["/home"], authAppUrl: process.env.AUTH_APP_URL, callbackUrl: process.env.CALLBACK_URL, matcher: [ '/content-library/:path*', '/another-protected-route/:path*', ], });
export { middleware, config };
