From 85c0a7bf38fa11f83f490b11bff3f34b114b536f Mon Sep 17 00:00:00 2001 From: BlankParticle Date: Sun, 8 Sep 2024 12:34:45 +0530 Subject: [PATCH] feat: add custom headers option to serve static --- src/middleware/serve-static/index.test.ts | 6 ++++++ src/middleware/serve-static/index.ts | 10 ++++++++++ 2 files changed, 16 insertions(+) diff --git a/src/middleware/serve-static/index.test.ts b/src/middleware/serve-static/index.test.ts index efae1aeb5..3187e3c73 100644 --- a/src/middleware/serve-static/index.test.ts +++ b/src/middleware/serve-static/index.test.ts @@ -18,6 +18,9 @@ describe('Serve Static Middleware', () => { isDir: (path) => { return path === 'static/hello.world' }, + headers: (c) => ({ + 'Cache-Control': c.req.path === '/static/hello.html' ? 'public, max-age=31536000' : undefined, + }), }) app.get('/static/*', serveStatic) @@ -30,6 +33,7 @@ describe('Serve Static Middleware', () => { const res = await app.request('/static/hello.html') expect(res.status).toBe(200) expect(res.headers.get('Content-Type')).toMatch(/^text\/html/) + expect(res.headers.get('Cache-Control')).toBe('public, max-age=31536000') expect(await res.text()).toBe('Hello in ./static/hello.html') }) @@ -52,6 +56,7 @@ describe('Serve Static Middleware', () => { expect(res.status).toBe(200) expect(res.headers.get('Content-Type')).toMatch(/^text\/html/) expect(await res.text()).toBe('Hello in ./static/hello.world/index.html') + expect(res.headers.get('Cache-Control')).toBe(null) }) it('Should decode URI strings - /static/%E7%82%8E.txt', async () => { @@ -65,6 +70,7 @@ describe('Serve Static Middleware', () => { expect(res.status).toBe(404) expect(await res.text()).toBe('404 Not Found') expect(getContent).toBeCalledTimes(1) + expect(res.headers.get('Cache-Control')).toBe(null) }) it('Should not allow a directory traversal - /static/%2e%2e/static/hello.html', async () => { diff --git a/src/middleware/serve-static/index.ts b/src/middleware/serve-static/index.ts index 1e3e78569..74ed69135 100644 --- a/src/middleware/serve-static/index.ts +++ b/src/middleware/serve-static/index.ts @@ -12,6 +12,7 @@ export type ServeStaticOptions = { root?: string path?: string mimes?: Record + headers?: (c: Context) => Record rewriteRequestPath?: (path: string) => string onNotFound?: (path: string, c: Context) => void | Promise } @@ -85,6 +86,15 @@ export const serveStatic = ( } } + const headers = options.headers?.(c) + if (headers) { + for (const [key, value] of Object.entries(headers)) { + if (value) { + c.header(key, value) + } + } + } + if (content instanceof Response) { return c.newResponse(content.body, content) }