fastify set reply headers for all routes

Viewed 2899

For every route I have to type the same headers as shown below. Is there a way to set these headers globally so that they are used by default for every route and can be overridden on a per-route basis?

fastify.post("/api/users", async (request, reply) => {
    try {
        reply
            .code(200)
             header("Access-Control-Allow-Origin", "http://localhost:3000")
            .header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")
            .header("Content-Type", "application/json; charset=utf-8")
            .send();
    } catch (error) {
        reply
            .code(400)
            .header("Access-Control-Allow-Origin", "http://localhost:3000")
            .header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")
            .header("Content-Type", "application/json; charset=utf-8")
            .send();
    }
});
1 Answers

You can set some headers before use send()


fastify.addHook('preHandler', (req, repy, done) => {
  reply.header("key", "value")
  done()
})

fastify.post("api/users", async (req, reply) => {
  try {
    reply.code(200).send()
  } catch (err) {
    reply.code(400).send()
  }
})

But I saw you want to use CORS, why not use fastify-cors ?

Related