0

whats the difference between these two examples ? And which should you prefer to use ?

import Fastify from 'fastify';

const fastify = Fastify({
  logger: true
});

fastify.get('/', async () => {
  return { message: 'Hello' }
});

const main = async () => {
  await fastify.listen({port: 3000});
};

second

const fastify = require('fastify')({logger: true});

fastify.get('/', async (req, reply) => {
  reply.send({message: 'Hello'})
});

const main = async () => {
  await fastify.listen({port: 3000});
};

So in the first we use import and not reply.send

in the second I use require and reply.send

I watched two tutorials and thats why I am asking which should I use and what you prefer and whats the difference ?

  • The only difference is using ESM imports or Common JS require, that has been [answered elsewhere](https://stackoverflow.com/q/31354559/1318694) – Matt Apr 26 '23 at 00:23

1 Answers1

1

As written in comments, the main difference is ESM vs CJS syntax, but as you spotted in the 1st example reply.send() is not used

As a general rule you can say:

  • When there is an async handler, returning the response payload is the best choice.
  • When there is no async handler, responding by using reply.send() is the best choice.

Because:

  • if you have callback style processing, you need to use reply.send()
  • if you can use async/await, returning is more readable

Because: if you write:

fastify.get('/', async (req, reply) => {
  reply.send({message: 'Hello'})
  return { farewell: 'bye' }
});

What do you expect as output? - reply.send will win because it is more "lower level" thing.

I explain it more deeply in my book about fastify (see my profile as I don't want to spam link here)

Manuel Spigolon
  • 11,003
  • 5
  • 50
  • 73