elysiajs / elysia

Ergonomic Framework for Humans
https://elysiajs.com
MIT License
9.23k stars 198 forks source link

`set.headers` is ignored in some situations #618

Closed Coachonko closed 3 months ago

Coachonko commented 3 months ago

What version of Elysia.JS is running?

1.0.14

What platform is your computer?

Linux 5.14.0-362.24.1.el9_3.x86_64 x86_64 x86_64

What steps can reproduce the bug?

import { join } from 'bun:path'
import Elysia from 'elysia'

export function tryFiles (elysiaContext, publicDir, handler) {
  const absolutePath = join(process.cwd(), publicDir, elysiaContext.path)

  const allowedBasePath = join(process.cwd(), publicDir, '/')
  if (!absolutePath.startsWith(allowedBasePath)) {
    return elysiaContext.error(403) // 'Forbidden'
  }

  if (absolutePath === allowedBasePath) {
    return handler(elysiaContext)
  }

  const file = Bun.file(absolutePath)
  if (file.size === 0) {
    return handler(elysiaContext)
  }

  return file
}

export async function respond (elysiaContext) {
  try {
    const body = `<!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <base href="/">
        <title>Response</title>
      </head>
      <body>
        This is an HTML response
      </body>
    </html>`

    elysiaContext.set.headers['Content-Type'] = 'text/html'
    return body
    // return new Response(body, { headers: { 'Content-Type': 'text/html' } }) this always returns text/html as expected
  } catch (err) {
    console.error(err)
  }
}

const app = new Elysia()

if (process.env.BUN_ENV === 'production') {
  app.get('*', (ctx) => respond(ctx))
} else {
  app.get('*', (ctx) => tryFiles(ctx, 'build', respond))
}

app.listen(8080)

When BUN_ENV !== 'production' then body is returned with Content-Type set as text/plain despite it being set as text/html

I do not think it is my fault, but it might be.

What is the expected behavior?

body is returned as text/html

What do you see instead?

body is returned as text/plain

Additional information

No response

Coachonko commented 3 months ago

Problem is solved by defining app using method chaining on Elysia constructor