Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add custom headers option to serve static #3395

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions src/middleware/serve-static/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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')
})

Expand All @@ -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 () => {
Expand All @@ -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 () => {
Expand Down
10 changes: 10 additions & 0 deletions src/middleware/serve-static/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ export type ServeStaticOptions<E extends Env = Env> = {
root?: string
path?: string
mimes?: Record<string, string>
headers?: (c: Context) => Record<string, string | undefined>
rewriteRequestPath?: (path: string) => string
onNotFound?: (path: string, c: Context<E>) => void | Promise<void>
}
Expand Down Expand Up @@ -85,6 +86,15 @@ export const serveStatic = <E extends Env = Env>(
}
}

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)
}
Expand Down
Loading