Skip to content

Lifecycle is not interrupted when onSend executes asynchronously #1733

@ericmacfa

Description

@ericmacfa

🐛 Bug Report

When an instance onSend hook executes asynchronously, responding from a route hook does not always prevent the route handler from being called.

To Reproduce

Setup

  1. npm init -y && npm i -S fastify@2.6.0

  2. Add the code from this gist to index.js

    Bare-bones snippet

    const fastify = require('fastify')();
    
    // This issue occurs with both callback and promise based `onSend` hooks
    fastify.addHook('onSend', (request, reply, payload, done) => {
        setTimeout(() => {
            done(null, payload);
        }, 50);
    });
    fastify.route({
        method: 'GET',
        path: '/',
        preHandler: async function(request, reply) {
            console.log('GET / -> preHandler()');
            reply.redirect('/login');
        },
        handler: function(request, reply) {
            console.log('GET / -> handler() !! This should never be shown !!');
            reply.send({ hello: 'world' });
        }
    });
    fastify.route({
        method: 'GET',
        path: '/login',
        handler: function(request, reply) {
            console.log('GET /login -> handler()');
            reply.send('Please log in\n');
        }
    });
    fastify.listen(3000);

  3. node ./index.js

Steps to reproduce

  1. curl -L localhost:3000 (Or via a browser, postman, etc.)
  2. Notice that the / route handler was called, even though we responded in the preHandler hook.
    server listening on port 3000
    GET / -> preHandler()
    GET / -> handler() !! This should never be shown !!
    GET /login -> handler()
    

Additional notes (from gist code comments)

  • This issue occurs when either the callback or the promise based onSend hook is used.
  • This issue occurs when the promise based preHandler hook is used, but not when the callback based version is used.

Expected behavior

  1. curl -L localhost:3000
  2. The handler for the / route should not be called.
    server listening on port 3000
    GET / -> preHandler()
    GET /login -> handler()
    

Your Environment

  • node version: 10.16.0
  • fastify version: 2.6.0
  • os: Mac

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugConfirmed bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions