Skip to content

Bug(optimize): Request body API removal affects outside of the handler #64

Open

Description

@yusukebe

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 { type Context, Hono } from 'hono'

const app = new Hono()

const service = async (c: Context) => {
  if (c.req.method !== 'POST') {
    return c.json({ message: 'Only POST requests are allowed' }, 405)
 }
  const receivedData = await c.req.json()
  // do something with receivedData
  return receivedData
}

app.all('/', async (c) => {
  const result = await service(c)
  return c.json({ status: 'success', result })
})

export default app

The repo: https://github.com/yusukebe/hono-cli-request-body-api-removal-bug

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.

Activity

  1. yusukebe commented on Jan 3, 2026

    @yusukebe
    MemberAuthor

    Hey @usualoma, Happy New Year!

    What do you think of this problem?

  2. usualoma commented on Jan 3, 2026

    @usualoma
    Member

    Hey @yusukebe! Happy New Year 🎍

    Ah yes, that use case.

    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.

    diff --git i/src/commands/optimize/index.test.ts w/src/commands/optimize/index.test.ts
    index 973171f..799ab48 100644
    --- i/src/commands/optimize/index.test.ts
    +++ w/src/commands/optimize/index.test.ts
    @@ -327,6 +327,28 @@ describe('optimizeCommand', () => {
           expect(content).toMatch(/parseBody/)
         })
     
    +    it('should keep request body APIs when all method is used', { timeout: 0 }, async () => {
    +      writePackageJSON(dir)
    +      await npmInstall()
    +      writeFileSync(
    +        join(dir, './src/index.ts'),
    +        `
    +          import { Hono } from 'hono'
    +          const app = new Hono()
    +          app.get('/', (c) => c.text('Hello'))
    +          app.all('/data', async (c) => {
    +            const body = await c.req.json()
    +            return c.json(body)
    +          })
    +          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',
           { timeout: 0 },
    diff --git i/src/commands/optimize/index.ts w/src/commands/optimize/index.ts
    index 27cf461..0d49795 100644
    --- i/src/commands/optimize/index.ts
    +++ w/src/commands/optimize/index.ts
    @@ -196,7 +196,7 @@ export class Hono extends HonoBase {
             const removeRequestBodyApi =
               options.requestBodyApiRemoval !== false &&
               app.routes.every(({ method }) =>
    -            [METHOD_NAME_ALL, 'GET', 'HEAD', 'OPTIONS'].includes(method.toUpperCase())
    +            ['GET', 'HEAD', 'OPTIONS'].includes(method.toUpperCase())
               )
             const unusedHonoMethods: Record<string, number> = (
               app as Hono & { unusedMethods: Record<string, number> }
  3. usualoma commented on Jan 3, 2026

    @usualoma
    Member

    Ah, sorry, with the one above, just using use stops it from being optimised.

    It might be best to make use subject to optimisation and do it like this:

    diff --git i/src/commands/optimize/index.test.ts w/src/commands/optimize/index.test.ts
    index 973171f..fbf31e5 100644
    --- i/src/commands/optimize/index.test.ts
    +++ w/src/commands/optimize/index.test.ts
    @@ -292,6 +292,9 @@ describe('optimizeCommand', () => {
               `
               import { Hono } from 'hono'
               const app = new Hono()
    +          app.use(async (c, next) => {
    +            await next()
    +          })
               app.get('/', (c) => c.text('Hello'))
               app.options('/cors', (c) => c.text('OK'))
               export default app
    @@ -327,6 +330,28 @@ describe('optimizeCommand', () => {
           expect(content).toMatch(/parseBody/)
         })
     
    +    it('should keep request body APIs when all method is used', { timeout: 0 }, async () => {
    +      writePackageJSON(dir)
    +      await npmInstall()
    +      writeFileSync(
    +        join(dir, './src/index.ts'),
    +        `
    +          import { Hono } from 'hono'
    +          const app = new Hono()
    +          app.get('/', (c) => c.text('Hello'))
    +          app.all('/data', async (c) => {
    +            const body = await c.req.json()
    +            return c.json(body)
    +          })
    +          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',
           { timeout: 0 },
    diff --git i/src/commands/optimize/index.ts w/src/commands/optimize/index.ts
    index 27cf461..acf5649 100644
    --- i/src/commands/optimize/index.ts
    +++ w/src/commands/optimize/index.ts
    @@ -195,8 +195,10 @@ 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())
    +          app.routes.every(
    +            ({ method, path }) =>
    +              ['GET', 'HEAD', 'OPTIONS'].includes(method.toUpperCase()) ||
    +              (method === METHOD_NAME_ALL && path === '/*')
               )
             const unusedHonoMethods: Record<string, number> = (
               app as Hono & { unusedMethods: Record<string, number> }
  4. yusukebe commented on Jan 4, 2026

    @yusukebe
    MemberAuthor

    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.

    app.use(async (c, next) => {
      if (c.req.method === 'POST') {
        console.log('Received a POST request, body is:', await c.req.text())
      }
      await next()
    })
    
    app.get('/', (c) => {
      return c.json({ message: 'Hello, World!' })
    })
  5. usualoma commented on Jan 6, 2026

    @usualoma
    Member

    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
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions