You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Bug(optimize): Request body API removal affects outside of the handler #64
This may be not a real bug, but I had a problem. When I use @hono/mcp in my Hono app, optimize it with the hono optimize command, and deploy the optimized code. But it does not work well now. I investigated and found that the @hono/mcp uses request body APIs in the functions outside of the handler. So, if I added the option --no-request-body-api-removal, it works well.
This is a minimal code to reproduce my problem:
import{typeContext,Hono}from'hono'constapp=newHono()constservice=async(c: Context)=>{if(c.req.method!=='POST'){returnc.json({message: 'Only POST requests are allowed'},405)}constreceivedData=awaitc.req.json()// do something with receivedDatareturnreceivedData}app.all('/',async(c)=>{constresult=awaitservice(c)returnc.json({status: 'success', result })})exportdefaultapp
There will likely be some similar cases. If the user encounters this problem, it's hard to identify the cause and solution. So, making --no-request-body-api-removal as default will be a good idea, I think.
In the current main branch, METHOD_NAME_ALL is included in the "list of methods whose body handling may be removed". How about a change to exclude this?
If this seems acceptable, I think --no-request-body-api-removal should remain optional for now.
Thank you for the comment! Ah middleware... The code seems nice, but what about the following code? Will the request body API be removed? If so, the behavior will be unintended.
app.use(async(c,next)=>{if(c.req.method==='POST'){console.log('Received a POST request, body is:',awaitc.req.text())}awaitnext()})app.get('/',(c)=>{returnc.json({message: 'Hello, World!'})})
Hi @yusukebe
Thanks for pointing that out! I see, that kind of middleware is indeed possible.
In the example case, under normal conditions, it likely doesn't accept POST requests. However, if it receives a malicious POST request intended for attack, it crashes with a runtime error. As you mentioned, this is difficult to debug and also seems problematic from a security perspective.
So, how about the following approach?
Be stricter: Only automatically remove the request body API when the application only uses GET/HEAD/OPTIONS
Introduce a --request-body-api-removal option with the options auto | force | disable
commit 9f867a0dbfb30134f85add6f318f3f58cb39af8f
Author: Taku Amano <taku@taaas.jp>
Date: Wed Jan 7 07:49:55 2026 +0900
feat(optimize): add request body API removal mode option
diff --git a/src/commands/optimize/index.test.ts b/src/commands/optimize/index.test.ts
index 973171f..cf42183 100644
--- a/src/commands/optimize/index.test.ts+++ b/src/commands/optimize/index.test.ts@@ -327,8 +327,33 @@ describe('optimizeCommand', () => {
expect(content).toMatch(/parseBody/)
})
+ it('should keep request body APIs when middleware is used', { timeout: 0 }, async () => {+ writePackageJSON(dir)+ await npmInstall()+ writeFileSync(+ join(dir, './src/index.ts'),+ `+ import { Hono } from 'hono'+ const app = new Hono()+ app.use(async (c, next) => {+ if (c.req.method === 'POST') {+ const body = await c.req.json()+ c.set('body', body)+ }+ await next()+ })+ app.get('/', (c) => c.text('Hello'))+ export default app+ `+ )+ await program.parseAsync(['node', 'hono', 'optimize'])++ const content = readFileSync(join(dir, './dist/index.js'), 'utf-8')+ expect(content).toMatch(/parseBody/)+ })+
it(
- 'should keep request body APIs when --no-request-body-api-removal is specified',+ 'should keep request body APIs when --request-body-api-removal disable is specified',
{ timeout: 0 },
async () => {
writePackageJSON(dir)
@@ -342,12 +367,50 @@ describe('optimizeCommand', () => {
export default app
`
)
- await program.parseAsync(['node', 'hono', 'optimize', '--no-request-body-api-removal'])+ await program.parseAsync([+ 'node',+ 'hono',+ 'optimize',+ '--request-body-api-removal',+ 'disable',+ ])
const content = readFileSync(join(dir, './dist/index.js'), 'utf-8')
expect(content).toMatch(/parseBody/)
}
)
++ it(+ 'should remove request body APIs when --request-body-api-removal force is specified',+ { timeout: 0 },+ async () => {+ writePackageJSON(dir)+ await npmInstall()+ writeFileSync(+ join(dir, './src/index.ts'),+ `+ import { Hono } from 'hono'+ const app = new Hono()+ app.post('/data', async (c) => {+ const body = await c.req.json()+ return c.json(body)+ })+ export default app+ `+ )+ await program.parseAsync([+ 'node',+ 'hono',+ 'optimize',+ '--request-body-api-removal',+ 'force',+ ])++ const content = readFileSync(join(dir, './dist/index.js'), 'utf-8')+ expect(content).not.toMatch(/parseBody/)+ expect(content).not.toMatch(/#cachedBody/)+ }+ )
})
describe('Hono API removal', () => {
diff --git a/src/commands/optimize/index.ts b/src/commands/optimize/index.ts
index 27cf461..6f6b57e 100644
--- a/src/commands/optimize/index.ts+++ b/src/commands/optimize/index.ts@@ -9,7 +9,6 @@ import type {
import type { Command } from 'commander'
import * as esbuild from 'esbuild'
import type { Hono } from 'hono'
-import { METHOD_NAME_ALL } from 'hono/router'
import { buildInitParams, serializeInitParams } from 'hono/router/reg-exp-router'
import MagicString from 'magic-string'
import { execFile } from 'node:child_process'
@@ -39,8 +38,9 @@ export function optimizeCommand(program: Command) {
.option('-o, --outfile [outfile]', 'output file', 'dist/index.js')
.option('-m, --minify', 'minify output file')
.option(
- '--no-request-body-api-removal',- 'do not remove request body APIs even if they are not needed'+ '--request-body-api-removal [mode]',+ 'request body API removal mode (auto | force | disable, default: auto)',+ 'auto'
)
.option('--no-hono-api-removal', 'do not remove Hono APIs even if they are not used')
.option(
@@ -55,7 +55,7 @@ export function optimizeCommand(program: Command) {
outfile: string
minify?: boolean
target: string
- requestBodyApiRemoval: boolean+ requestBodyApiRemoval: 'auto' | 'force' | 'disable'
honoApiRemoval: boolean
contextResponseApiRemoval: boolean
}
@@ -194,10 +194,11 @@ export class Hono extends HonoBase {
const removed = []
const removeRequestBodyApi =
- options.requestBodyApiRemoval !== false &&- app.routes.every(({ method }) =>- [METHOD_NAME_ALL, 'GET', 'HEAD', 'OPTIONS'].includes(method.toUpperCase())- )+ options.requestBodyApiRemoval === 'force' ||+ (options.requestBodyApiRemoval === 'auto' &&+ app.routes.every(({ method }) =>+ ['GET', 'HEAD', 'OPTIONS'].includes(method.toUpperCase())+ ))
const unusedHonoMethods: Record<string, number> = (
app as Hono & { unusedMethods: Record<string, number> }
).unusedMethods
Activity
yusukebe commentedon Jan 3, 2026
Hey @usualoma, Happy New Year!
What do you think of this problem?
usualoma commentedon Jan 3, 2026
Hey @yusukebe! Happy New Year 🎍
Ah yes, that use case.
In the current main branch,
METHOD_NAME_ALLis included in the "list of methods whose body handling may be removed". How about a change to exclude this?If this seems acceptable, I think
--no-request-body-api-removalshould remain optional for now.usualoma commentedon Jan 3, 2026
Ah, sorry, with the one above, just using
usestops it from being optimised.It might be best to make
usesubject to optimisation and do it like this:yusukebe commentedon Jan 4, 2026
Hi @usualoma
Thank you for the comment! Ah middleware... The code seems nice, but what about the following code? Will the request body API be removed? If so, the behavior will be unintended.
usualoma commentedon Jan 6, 2026
Hi @yusukebe
Thanks for pointing that out! I see, that kind of middleware is indeed possible.
In the example case, under normal conditions, it likely doesn't accept
POSTrequests. However, if it receives a maliciousPOSTrequest intended for attack, it crashes with a runtime error. As you mentioned, this is difficult to debug and also seems problematic from a security perspective.So, how about the following approach?
--request-body-api-removaloption with the optionsauto | force | disablecommit 9f867a0dbfb30134f85add6f318f3f58cb39af8f Author: Taku Amano <taku@taaas.jp> Date: Wed Jan 7 07:49:55 2026 +0900 feat(optimize): add request body API removal mode option diff --git a/src/commands/optimize/index.test.ts b/src/commands/optimize/index.test.ts index 973171f..cf42183 100644 --- a/src/commands/optimize/index.test.ts +++ b/src/commands/optimize/index.test.ts @@ -327,8 +327,33 @@ describe('optimizeCommand', () => { expect(content).toMatch(/parseBody/) }) + it('should keep request body APIs when middleware is used', { timeout: 0 }, async () => { + writePackageJSON(dir) + await npmInstall() + writeFileSync( + join(dir, './src/index.ts'), + ` + import { Hono } from 'hono' + const app = new Hono() + app.use(async (c, next) => { + if (c.req.method === 'POST') { + const body = await c.req.json() + c.set('body', body) + } + await next() + }) + app.get('/', (c) => c.text('Hello')) + export default app + ` + ) + await program.parseAsync(['node', 'hono', 'optimize']) + + const content = readFileSync(join(dir, './dist/index.js'), 'utf-8') + expect(content).toMatch(/parseBody/) + }) + it( - 'should keep request body APIs when --no-request-body-api-removal is specified', + 'should keep request body APIs when --request-body-api-removal disable is specified', { timeout: 0 }, async () => { writePackageJSON(dir) @@ -342,12 +367,50 @@ describe('optimizeCommand', () => { export default app ` ) - await program.parseAsync(['node', 'hono', 'optimize', '--no-request-body-api-removal']) + await program.parseAsync([ + 'node', + 'hono', + 'optimize', + '--request-body-api-removal', + 'disable', + ]) const content = readFileSync(join(dir, './dist/index.js'), 'utf-8') expect(content).toMatch(/parseBody/) } ) + + it( + 'should remove request body APIs when --request-body-api-removal force is specified', + { timeout: 0 }, + async () => { + writePackageJSON(dir) + await npmInstall() + writeFileSync( + join(dir, './src/index.ts'), + ` + import { Hono } from 'hono' + const app = new Hono() + app.post('/data', async (c) => { + const body = await c.req.json() + return c.json(body) + }) + export default app + ` + ) + await program.parseAsync([ + 'node', + 'hono', + 'optimize', + '--request-body-api-removal', + 'force', + ]) + + const content = readFileSync(join(dir, './dist/index.js'), 'utf-8') + expect(content).not.toMatch(/parseBody/) + expect(content).not.toMatch(/#cachedBody/) + } + ) }) describe('Hono API removal', () => { diff --git a/src/commands/optimize/index.ts b/src/commands/optimize/index.ts index 27cf461..6f6b57e 100644 --- a/src/commands/optimize/index.ts +++ b/src/commands/optimize/index.ts @@ -9,7 +9,6 @@ import type { import type { Command } from 'commander' import * as esbuild from 'esbuild' import type { Hono } from 'hono' -import { METHOD_NAME_ALL } from 'hono/router' import { buildInitParams, serializeInitParams } from 'hono/router/reg-exp-router' import MagicString from 'magic-string' import { execFile } from 'node:child_process' @@ -39,8 +38,9 @@ export function optimizeCommand(program: Command) { .option('-o, --outfile [outfile]', 'output file', 'dist/index.js') .option('-m, --minify', 'minify output file') .option( - '--no-request-body-api-removal', - 'do not remove request body APIs even if they are not needed' + '--request-body-api-removal [mode]', + 'request body API removal mode (auto | force | disable, default: auto)', + 'auto' ) .option('--no-hono-api-removal', 'do not remove Hono APIs even if they are not used') .option( @@ -55,7 +55,7 @@ export function optimizeCommand(program: Command) { outfile: string minify?: boolean target: string - requestBodyApiRemoval: boolean + requestBodyApiRemoval: 'auto' | 'force' | 'disable' honoApiRemoval: boolean contextResponseApiRemoval: boolean } @@ -194,10 +194,11 @@ export class Hono extends HonoBase { const removed = [] const removeRequestBodyApi = - options.requestBodyApiRemoval !== false && - app.routes.every(({ method }) => - [METHOD_NAME_ALL, 'GET', 'HEAD', 'OPTIONS'].includes(method.toUpperCase()) - ) + options.requestBodyApiRemoval === 'force' || + (options.requestBodyApiRemoval === 'auto' && + app.routes.every(({ method }) => + ['GET', 'HEAD', 'OPTIONS'].includes(method.toUpperCase()) + )) const unusedHonoMethods: Record<string, number> = ( app as Hono & { unusedMethods: Record<string, number> } ).unusedMethods