A lightweight, zero-dependency route pattern matcher for JavaScript and TypeScript applications.
npm install easy-route-matcherimport { createRouteMatcher } from 'easy-route-matcher';
// Create matchers for different route groups
const isAuthRoute = createRouteMatcher([
'/auth/login',
'/auth/register',
'/auth/forgot-password'
]);
const isAdminRoute = createRouteMatcher([
'/admin(.*)' // Matches any route starting with /admin
]);
const isPublicRoute = createRouteMatcher([
'/',
'/about',
'/contact'
]);
// Use the matchers
const pathname = '/admin/users';
if (isAdminRoute(pathname)) {
// Handle admin route
console.log('Admin route detected');
}
if (!isAuthRoute(pathname) && !isPublicRoute(pathname)) {
// Require authentication
console.log('Protected route - authentication required');
}Creates a route matcher function that tests if a pathname matches any of the provided patterns.
patterns: Array of route patterns. Supports:- Exact matches:
/about,/contact - Regex patterns:
/admin(.*),/api/users/[0-9]+
- Exact matches:
A function that takes a pathname string and returns a boolean indicating if it matches any pattern.
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { createRouteMatcher } from 'easy-route-matcher';
const isPublicRoute = createRouteMatcher([
'/',
'/login',
'/register'
]);
export function middleware(request: NextRequest) {
const { pathname } = request.nextUrl;
if (!isPublicRoute(pathname)) {
// Redirect to login if not authenticated
return NextResponse.redirect(new URL('/login', request.url));
}
return NextResponse.next();
}const express = require('express');
const { createRouteMatcher } = require('easy-route-matcher');
const app = express();
const requiresAuth = createRouteMatcher([
'/api/user(.*)',
'/dashboard(.*)',
'/settings'
]);
app.use((req, res, next) => {
if (requiresAuth(req.path) && !req.session.user) {
return res.status(401).json({ error: 'Authentication required' });
}
next();
});This package is written in TypeScript and includes full type definitions.
MIT