UNPKG

nextjs-multi-middleware

Version:

A utility to easily chain and compose multiple middleware functions in Next.js.

2 lines (1 loc) 1.13 kB
import{NextResponse as h}from"next/server";import{match as q}from"path-to-regexp";function $(p,m={}){let{debug:w=!1}=m,a=w?console.log:()=>{},M=p.map(o=>typeof o=="function"?{handler:o}:o);return async function(o,E){let c,R=0,d=o,i=E,r=async(s,f)=>{let n;s instanceof Error?n=s:s&&(a("[chain] Next called with a new request."),d=s,f&&(i=f));let N=M[R++];if(!N){if(n)throw n;return}let{handler:t,matcher:x}=N;if(!n){let e=!0;if(x&&(typeof x=="function"?e=x(d):e=q(x,{decode:decodeURIComponent})(d.nextUrl.pathname)!==!1,a(`[chain] Middleware ${t.name||"anonymous"}: matcher evaluated to ${e}`)),!e)return r()}try{if(n)return t.length===4?(a(`[chain] Executing error handler ${t.name||"anonymous"}`),await t(n,d,i,(u,l,v)=>u?r(u):r(l,v))):r(n);if(t.length<=2){a(`[chain] Executing standard middleware ${t.name||"anonymous"}`);let e=await t(d,i);return e instanceof h?e:await r()}else if(t.length===3)return a(`[chain] Executing custom middleware ${t.name||"anonymous"}`),await t(d,i,(u,l)=>r(u,l))}catch(e){return a(`[chain] Error in middleware ${t.name||"anonymous"}:`,e),r(e)}};return c=await r(),c||h.next()}}export{$ as chain};