How to use fastify - 10 common examples

To help you get started, we’ve selected a few fastify examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github xtremespb / zoia2 / src / shared / api / api.js View on Github external
let pino;
    try {
        secure = await fs.readJSON(path.resolve(`${__dirname}/../etc/secure.json`));
        config = await fs.readJSON(path.resolve(`${__dirname}/../static/etc/config.json`));
        pino = Pino({
            level: secure.loglevel
        });
    } catch (e) {
        // eslint-disable-next-line no-console
        console.error(e);
        process.exit(1);
    }
    try {
        pino.info(`Starting`);
        // Create Fastify instance
        const fastify = Fastify({
            logger,
            trustProxy: secure.trustProxy
        });
        // Create Nodemailer instance
        const mailer = nodemailer.createTransport(secure.mailer);
        // Decorate Fastify with configuration and helpers
        fastify.decorate('zoiaConfig', config);
        fastify.decorate('zoiaConfigSecure', secure);
        fastify.decorateRequest('zoiaConfig', config);
        fastify.decorateRequest('zoiaConfigSecure', secure);
        fastify.decorate('zoiaMailer', mailer);
        fastify.decorateRequest('zoiaMailer', mailer);
        fastify.decorate('xxhash', data => xxhash(data, secure.randomInt));
        Object.keys(response).map(i => fastify.decorateReply(i, response[i]));
        Object.keys(loggerHelpers).map(i => fastify.decorateReply(i, loggerHelpers[i]));
        Object.keys(auth).map(i => fastify.decorateRequest(i, auth[i]));
github HospitalRun / hospitalrun-server / src / index.ts View on Github external
// we need this file because of this issue: https://github.com/fastify/fastify-cli/issues/131
import 'make-promises-safe'
import blipp from 'fastify-blipp'

import Fastify from 'fastify'

import app from './app'

console.time('Boot Time')
const fastify = Fastify(app.options)

fastify.register(blipp)
fastify.register(app)

fastify.listen((process.env.PORT as any) || 3000, '0.0.0.0', err => {
  if (err) {
    console.log(err)
    process.exit(1)
  }
  fastify.blipp()

  console.timeEnd('Boot Time')
  console.log(`Server listening on port ${(fastify.server as any).address().port}`)
})
github xtremespb / zoia2 / src / shared / marko / src / index.js View on Github external
let pino;
    try {
        secure = await fs.readJSON(path.resolve(`${__dirname}/../etc/secure.json`));
        config = await fs.readJSON(path.resolve(`${__dirname}/../static/etc/config.json`));
        pino = Pino({
            level: secure.loglevel
        });
        pino.info(`Starting`);
    } catch (e) {
        // eslint-disable-next-line no-console
        console.error(e);
        process.exit(1);
    }
    try {
        // Create Fastify instance
        const fastify = Fastify({
            logger,
            trustProxy: secure.trustProxy,
            ignoreTrailingSlash: true
        });
        // Decorate Fastify with configuration and helpers
        fastify.decorate('zoiaConfig', config);
        fastify.decorate('zoiaConfigSecure', secure);
        fastify.decorateRequest('zoiaConfig', config);
        fastify.decorateRequest('zoiaConfigSecure', secure);
        fastify.decorate('xxhash', data => xxhash(data, secure.randomInt));
        Object.keys(response).map(i => fastify.decorateReply(i, response[i]));
        Object.keys(loggerHelpers).map(i => fastify.decorateReply(i, loggerHelpers[i]));
        Object.keys(auth).map(i => fastify.decorateRequest(i, auth[i]));
        Object.keys(locale).map(i => fastify.decorateRequest(i, locale[i]));
        Object.keys(site).map(i => fastify.decorateRequest(i, site[i]));
        // Register FormBody and Multipart
github teppeis / duck / src / commands / serve.ts View on Github external
key: await promisify(readFile)(https.keyPath, "utf8"),
      cert: await promisify(readFile)(https.certPath, "utf8"),
    };
    // Use `any` because the types of http, https and http2 modules in Node.js are not compatible.
    // But it is not a big deal.
    if (http2) {
      server = fastify({
        ...opts,
        https: httpsOptions,
        http2: true,
      }) as fastify.FastifyInstance;
    } else {
      server = fastify({ ...opts, https: httpsOptions }) as any;
    }
  } else {
    server = fastify(opts);
  }

  // enable CORS at first
  server.use(cors());

  // customize log output
  server.addHook("onRequest", async ({ raw, log }, reply) => {
    const { method, url } = raw;
    if (url && url.startsWith(inputsUrlPath)) {
      // skip logging for static assets
      return;
    }
    log.info({ request: `${method} ${url}` }, "incoming request");
  });
  server.addHook("onResponse", async ({ raw, log }, reply) => {
    const { method, url, originalUrl } = raw;
github mvlabs / isomorphic-mithril / src / server-side-render / app.js View on Github external
.then(hashes => {
    const app = fastify()

    // Cookies
    app.register(cookieParser, err => {
      if (err) throw err
    })

    // Static content
    app.register((instance, opts, next) => {
      instance.register(serveStatic, {
        root: path.join(__dirname, '../../dist'),
        prefix: '/dist/'
      })
      next()
    })
    app.register((instance, opts, next) => {
      instance.register(serveStatic, {
github lbryio / lbry.tech / app / index.js View on Github external
import * as color from "colorette";
import compress from "fastify-compress";
import cors from "cors";
import fastify from "fastify";
import helmet from "fastify-helmet";
import ssr from "choo-ssr/fastify";
import statik from "fastify-static";
import websockets from "@inc/fastify-ws";

//  U T I L S

import handleSocketMessages from "./sockets";
import messageSlack from "~helper/slack";
import redirects from "~data/redirects.json";

const server = fastify({
  logger: {
    level: "warn",
    prettyPrint: process.env.NODE_ENV === "development",
    redact: ["req.headers.authorization"],
    serializers: {
      req(req) {
        return {
          headers: req.headers,
          hostname: req.hostname,
          method: req.method,
          remoteAddress: req.ip,
          remotePort: req.connection.remotePort,
          url: req.url
        };
      }
    }
github fastify / fastify-flash / tests / index.ts View on Github external
test('should set flash messages in one call.', async t => {
  t.plan(6)
  const fastify = Fastify()

  fastify.register(fastifySession, {
    key,
  })
  fastify.register(fastifyFlash)

  fastify.get('/test', (req, reply) => {
    const count = req.flash('warning', ['username required', 'password required'])
    t.equal(count, 2)

    const warning = reply.flash('warning')
    t.equal(warning.length, 2)

    t.equal(warning[0], 'username required')
    t.equal(warning[1], 'password required')
    reply.send({ warning })
github ChainSafe / lodestar / packages / lodestar / src / api / rest / index.ts View on Github external
private  setupServer(modules: IApiModules): IFastifyServer {
    const server = fastify.default({
      //TODO: somehow pass winston here
      logger: false,
      querystringParser: qs.parse
    }) as IFastifyServer;

    if(this.opts.cors) {
      const corsArr = this.opts.cors.split(",");
      server.register(fastifyCors, {
        origin: corsArr
      });
    }

    if(this.opts.api.includes(ApiNamespace.BEACON)) {
      //@ts-ignore
      server.register(routes.beacon, {prefix: "/node", modules});
    }
github fastify / fastify-plugin / index.js View on Github external
function checkVersion (version) {
  if (typeof version !== 'string') {
    throw new TypeError(`fastify-plugin expects a version string, instead got '${typeof version}'`)
  }

  var fastifyVersion
  try {
    fastifyVersion = require('fastify/package.json').version.replace(/-rc\.\d+/, '')
  } catch (_) {
    console.info('fastify not found, proceeding anyway')
  }

  if (fastifyVersion && !semver.satisfies(fastifyVersion, version)) {
    throw new Error(`fastify-plugin - expected '${version}' fastify version, '${fastifyVersion}' is installed`)
  }
}

fastify

Fast and low overhead web framework, for Node.js

MIT
Latest version published 26 days ago

Package Health Score

100 / 100
Full package analysis