Skip to content

LoisDuplain/easy-route-matcher

Repository files navigation

easy-route-matcher

A lightweight, zero-dependency route pattern matcher for JavaScript and TypeScript applications.

Installation

npm install easy-route-matcher

Usage

import { 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');
}

API

createRouteMatcher(patterns: string[]): RouteMatcher

Creates a route matcher function that tests if a pathname matches any of the provided patterns.

Parameters

  • patterns: Array of route patterns. Supports:
    • Exact matches: /about, /contact
    • Regex patterns: /admin(.*), /api/users/[0-9]+

Returns

A function that takes a pathname string and returns a boolean indicating if it matches any pattern.

Examples

Next.js Middleware

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();
}

Express.js Middleware

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();
});

TypeScript Support

This package is written in TypeScript and includes full type definitions.

License

MIT

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published