fastify / fastify-compress

Fastify compression utils
MIT License
202 stars 46 forks source link

Empty reply data in Fastify async route #237

Closed vitalikprac closed 2 years ago

vitalikprac commented 2 years ago

Prerequisites

Fastify version

4.2.0

Plugin version

6.1.0

Node.js version

16.15.0

Operating system

Windows 11

Browser

Chrome 102

Description

The route of fastify has handler function and it's work as expected.

fastify.get('/', (request, reply) => {
    reply.send('hello world');
})

Browser show the correct response headers and render 'hello world' to html image image

But if we changed handler function to async, it has strange behaviour

fastify.get('/', async(request, reply) => {
    reply.send('hello world');
})

In browser, response headers displays content-length: 0 image And browser says that request has no response data available

If I understand correctly https://github.com/fastify/fastify-compress/issues/140 issue should resolve my problem , but it would not work for me.

Steps to Reproduce

  1. Init project with yarn or npm
  2. Add fastify and @fastify/compress
    {
    "name": "test-fastify",
    "version": "1.0.0",
    "main": "node server.js",
    "type": "module",
    "license": "MIT",
    "dependencies": {
    "@fastify/compress": "^6.1.0",
    "fastify": "^4.2.0"
    }
    }
  3. $ yarn install
  4. Create server.js file
    
    import Fastify from 'fastify';
    import FastifyCompress from '@fastify/compress';

const fastify = Fastify(); await fastify.register(FastifyCompress, { threshold: 0 }); fastify.get('/', async(request, reply) => { reply.send('hello world'); }) await fastify.listen({ port: 3000 })

5. 
```bash 
$ yarn start
  1. Open Browser or Postman at http://localhost:3000
  2. View Response directly on the page or in Dev Tools image image

Expected Behavior

Browser should render hello world in async fastify handler as it does in non-async handler

mcollina commented 2 years ago

Thanks for reporting.

We changed the default behavior in V4, promoting a good promise hygiene.

Your promise returns undefined, so that's what you get.

fastify.get('/', async(request, reply) => {
  return 'hello world'
})

or

fastify.get('/', async(request, reply) => {
  reply.send('hello world')
  return reply
})
vitalikprac commented 2 years ago

Thanks, it's work for me. Also would be nice if you add example with async function to README for better developers experience.