UNPKG

@centinel/nextjs

Version:

Package designed to add Centinel Analytica functionality to Next.js applications

80 lines (79 loc) 2.44 kB
import { NextResponse } from 'next/server'; import { CentinelMiddleware } from './core/CentinelMiddleware'; let centinelWorker = undefined; export default async function middleware(req) { try { if (!centinelWorker) { throw new Error('Centinel worker not initialized. Use createCentinelMiddleware() to create your middleware.'); } const event = { request: req }; const centinelResult = await centinelWorker.validate(event); return centinelResult.response; } catch { return NextResponse.redirect(new URL('/block', req.url)); } } /** * Creates a Centinel middleware function with sequential validation. * The validation runs before allowing the request to proceed. * * @param config - Centinel configuration object * @returns Configured middleware function * * @example * ```typescript * // middleware.ts * import { createCentinelMiddleware } from '@centinel/nextjs'; * * export default createCentinelMiddleware({ * siteKey: process.env.CENTINEL_SITE_KEY!, * secretKey: process.env.CENTINEL_SECRET_KEY! * }); * * export const config = { * matcher: ['/api/:path*', '/dashboard/:path*'] * }; * ``` */ export function createCentinelMiddleware(config) { return async function centinelMiddleware(req) { try { if (!centinelWorker) { centinelWorker = new CentinelMiddleware(config); } const event = { request: req }; const centinelResult = await centinelWorker.validate(event); return centinelResult.response; } catch { return NextResponse.redirect(new URL('/block', req.url)); } }; } /** * Creates a Centinel middleware function using environment variables for configuration. * * @returns Configured middleware function * * @example * ```typescript * // middleware.ts * import { createCentinelMiddlewareFromEnv } from '@centinel/nextjs'; * * export default createCentinelMiddlewareFromEnv(); * * export const config = { * matcher: ['/api/:path*', '/dashboard/:path*'] * }; * ``` */ export function createCentinelMiddlewareFromEnv() { const config = { siteKey: process.env.CENTINEL_SITE_KEY, secretKey: process.env.CENTINEL_SECRET_KEY }; return createCentinelMiddleware(config); } // Export the core integration class for advanced usage export { CentinelMiddleware };