diff --git a/src/context.ts b/src/context.ts index 60b559974..7d9dc7d8a 100644 --- a/src/context.ts +++ b/src/context.ts @@ -131,8 +131,8 @@ export class Context< return (this._res ||= new Response('404 Not Found', { status: 404 })) } - set res(_res: Response) { - if (this._res) { + set res(_res: Response | undefined) { + if (this._res && _res) { this._res.headers.delete('content-type') this._res.headers.forEach((v, k) => { _res.headers.set(k, v) diff --git a/src/hono.test.ts b/src/hono.test.ts index 589ad3053..62673cb06 100644 --- a/src/hono.test.ts +++ b/src/hono.test.ts @@ -615,6 +615,36 @@ describe('Middleware', () => { expect(res.headers.get('x-after')).toBe('abc') }) }) + + describe('Overwrite the response from middleware after next()', () => { + const app = new Hono() + + app.use('/normal', async (c, next) => { + await next() + c.res = new Response('Middleware') + }) + + app.use('/overwrite', async (c, next) => { + await next() + c.res = undefined + c.res = new Response('Middleware') + }) + + app.get('*', (c) => { + c.header('x-custom', 'foo') + return c.text('Handler') + }) + + it('Should have the custom header', async () => { + const res = await app.request('/normal') + expect(res.headers.get('x-custom')).toBe('foo') + }) + + it('Should not have the custom header', async () => { + const res = await app.request('/overwrite') + expect(res.headers.get('x-custom')).toBe(null) + }) + }) }) describe('Builtin Middleware', () => {