From bbe038e3aa333cca9336829652948db39ca16b4c Mon Sep 17 00:00:00 2001 From: weeihan Date: Thu, 1 Oct 2026 08:13:59 +0800 Subject: [PATCH] fix(middleware): exempt manifest.json and sw.js from the auth matcher Logged-out requests were redirected to /login, and logged-in non-admin roles were bounced to their home page, which blocked PWA install and the service worker. Co-Authored-By: Claude Haiku 4.5 --- middleware.ts | 2 +- tests/middleware-matcher.test.ts | 20 ++++++++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) create mode 100644 tests/middleware-matcher.test.ts diff --git a/middleware.ts b/middleware.ts index 761d133..63f9afe 100644 --- a/middleware.ts +++ b/middleware.ts @@ -47,5 +47,5 @@ export async function middleware(request: NextRequest) { } export const config = { - matcher: ['/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)'], + matcher: ['/((?!_next/static|_next/image|favicon.ico|manifest\\.json$|sw\\.js$|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)'], } diff --git a/tests/middleware-matcher.test.ts b/tests/middleware-matcher.test.ts new file mode 100644 index 0000000..606e280 --- /dev/null +++ b/tests/middleware-matcher.test.ts @@ -0,0 +1,20 @@ +import { describe, it, expect } from 'vitest' +import { config } from '@/middleware' + +const re = new RegExp(`^${config.matcher[0]}$`) + +describe('middleware matcher', () => { + it.each(['/manifest.json', '/sw.js', '/_next/static/chunks/a.js', '/favicon.ico', '/icons/icon-192.png'])( + 'skips public asset %s so PWA files load without a session', + path => { + expect(re.test(path)).toBe(false) + }, + ) + + it.each(['/', '/login', '/hse/incidents', '/api/incidents', '/manifest.jsonx', '/app/sw.js'])( + 'still guards %s', + path => { + expect(re.test(path)).toBe(true) + }, + ) +})