Skip to content

Serverless docs on Google/Firebase cloud functions seems off #1042

Open
@0x80

Description

@0x80

The docs mention that you can integrate fastify like this:

const fastify = require("fastify")({
  logger: true,
})

const fastifyApp = async (request, reply) => {
  await registerRoutes(fastify)
  await fastify.ready()
  fastify.server.emit("request", request, reply)
}

exports.app = onRequest(fastifyApp)

But that seems very strange to me, because you are reregistering the routes on every request. And because people use Fastify for its performance, it seems odd that the docs do not mention anything.

I have now solved it like this

let fastifyApp: FastifyInstance | null = null;

async function initializeFastify() {
  if (fastifyApp) return fastifyApp;

  const fastify = Fastify({
    logger: envToLogger[environment] ?? true,
  });

  fastify.addContentTypeParser("application/json", {}, (req, body, done) => {
    // @ts-expect-error payload is not typed
    req.rawBody = payload.rawBody; // Useful if need to compute HMAC
    // @ts-expect-error body is not typed
    done(null, body.body);
  });

  await registerRoutes(fastify);
  await fastify.ready();

  fastifyApp = fastify;
  return fastifyApp;
}
export const webhooks = onRequest(
  async (req, res) => {
    const app = await initializeFastify();
    app.server.emit("request", req, res);
  }
);

Is Fastify so efficient in initializing that this omission is ok in the documentation? It seems very confusing for people like me who are not very familiar with Fastify..

Metadata

Metadata

Assignees

No one assigned

    Labels

    help wantedExtra attention is neededquestionFurther information is requested

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions