protect-nextjs-routes
v0.0.3
Published
CLI tool and library to manage route protection in Next.js applications
Maintainers
Readme
protect-nextjs-routes
A powerful CLI tool and library to manage route protection in Next.js applications with App Router support.
Features
- 🔒 Route Protection Management - Define and manage which routes require authentication
- 🎯 Next.js App Router Support - Built specifically for Next.js 13+ App Router
- 🛠️ CLI Tool - Interactive command-line interface for easy route configuration
- 📚 Library API - Programmatic access for middleware and custom logic
- 🌳 Route Tree Visualization - Visual representation of your route structure
- 🔍 Route Status Checking - Quickly check if routes are public or protected
- 📁 JSON Configuration - Simple JSON file for route protection mappings
Installation
Package Manager
# npm
npm install protect-nextjs-routes
# pnpm
pnpm add protect-nextjs-routes
# yarn
yarn add protect-nextjs-routesGlobal Installation (for CLI usage)
# npm
npm install -g protect-nextjs-routes
# pnpm
pnpm add -g protect-nextjs-routes
# yarn
yarn global add protect-nextjs-routesUsage
CLI Tool
Local Installation
npx protect-nextjs-routes
# or
pnpm exec protect-nextjs-routesGlobal Installation
protect-nextjs-routesThe CLI provides an interactive interface to:
- View your route tree structure
- Mark routes as public or protected
- Save configuration to
protect-routes.json
Library API
Basic Route Checking
import { getRouteStatus } from 'protect-nextjs-routes';
// Check if a route is protected
const status = getRouteStatus('/admin/dashboard');
console.log(status); // 'protected' | 'public'Middleware Integration
// middleware.ts
import { NextRequest } from 'next/server';
import { getRouteStatus } from 'protect-nextjs-routes';
export function middleware(request: NextRequest) {
const { pathname } = request.nextUrl;
const status = getRouteStatus(pathname);
if (status === 'protected') {
// Redirect to login or handle authentication
return Response.redirect(new URL('/login', request.url));
}
}Configuration Management
import { loadMapping, saveMapping } from 'protect-nextjs-routes/mapping';
// Load current route protection mapping
const mapping = await loadMapping('./protect-routes.json');
console.log(mapping); // { '/admin': 'protected', '/public': 'public' }
// Update and save mapping
mapping['/new-protected-route'] = 'protected';
await saveMapping('./protect-routes.json', mapping);Working with Constants
import {
ROUTE_STATUS_PUBLIC,
ROUTE_STATUS_PROTECTED,
STATUS_COLORS
} from 'protect-nextjs-routes/constants';
console.log(ROUTE_STATUS_PUBLIC); // 'public'
console.log(ROUTE_STATUS_PROTECTED); // 'protected'
console.log(STATUS_COLORS.public); // 'green'Configuration File
The package uses a protect-routes.json file in your project root:
{
"/admin": "protected",
"/admin/users": "protected",
"/api/auth": "public",
"/login": "public",
"/": "public"
}API Reference
Route Checking
getRouteStatus(pathname: string): Status
Returns the protection status of a given route.
- pathname: The route path to check
- Returns:
'public' | 'protected'
Configuration Management
loadMapping(filePath: string): Promise<Mapping>
Loads route protection mapping from a JSON file.
- filePath: Path to the configuration file
- Returns: Promise resolving to the route mapping object
saveMapping(filePath: string, mapping: Mapping): Promise<void>
Saves route protection mapping to a JSON file.
- filePath: Path to save the configuration file
- mapping: The route mapping object to save
Types
type Status = 'public' | 'protected';
type Color = 'green' | 'blue';
type Mapping = Record<string, Status>;
interface RouteNode {
name: string;
status: Status;
children: RouteNode[];
}Constants
ROUTE_STATUS_PUBLIC:'public'ROUTE_STATUS_PROTECTED:'protected'ROUTE_STATUSES: Array of valid status valuesDEFAULT_STATUS: Default status for unspecified routesSTATUS_COLORS: Color mapping for different statuses
Examples
Protecting Admin Routes
// middleware.ts
import { NextRequest, NextResponse } from 'next/server';
import { getRouteStatus } from 'protect-nextjs-routes';
export function middleware(request: NextRequest) {
const { pathname } = request.nextUrl;
// Check if route requires protection
if (getRouteStatus(pathname) === 'protected') {
// Check if user is authenticated (your logic here)
const isAuthenticated = checkAuth(request);
if (!isAuthenticated) {
return NextResponse.redirect(new URL('/login', request.url));
}
}
return NextResponse.next();
}
export const config = {
matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)'],
};Dynamic Configuration
import { loadMapping, saveMapping } from 'protect-nextjs-routes/mapping';
async function updateRouteProtection() {
const configPath = './protect-routes.json';
// Load current configuration
const mapping = await loadMapping(configPath);
// Add new protected routes
mapping['/admin/settings'] = 'protected';
mapping['/admin/analytics'] = 'protected';
// Make a route public
mapping['/help'] = 'public';
// Save updated configuration
await saveMapping(configPath, mapping);
console.log('Route protection updated!');
}Requirements
- Node.js: 20.0.0 or higher
- Next.js: 13.0.0 or higher (for App Router support)
Contributing
Contributions are welcome! Please visit the GitHub repository to:
- Report bugs
- Request features
- Submit pull requests
License
MIT © Pieter De Pauw
