kandi background
Explore Kits

fastify | Fast and low overhead web framework , for Node.js | Runtime Evironment library

 by   fastify JavaScript Version: v3.28.0 License: Non-SPDX

 by   fastify JavaScript Version: v3.28.0 License: Non-SPDX

Download this library from

kandi X-RAY | fastify Summary

fastify is a JavaScript library typically used in Institutions, Learning, Administration, Public Services, Server, Runtime Evironment, Nodejs applications. fastify has no bugs, it has no vulnerabilities and it has medium support. However fastify has a Non-SPDX License. You can install using 'npm i fastify' or download it from GitHub, npm.
Code for Fastify's v1.x is in branch 1.x, so all Fastify 1.x related changes should be based on branch 1.x. In a similar way, all Fastify v2.x related changes should be based on branch 2.x. Note .listen binds to the local host, localhost, interface by default (127.0.0.1 or ::1, depending on the operating system configuration). If you are running Fastify in a container (Docker, GCP, etc.), you may need to bind to 0.0.0.0. Be careful when deciding to listen on all interfaces; it comes with inherent security risks. See the documentation for more information.
Support
Support
Quality
Quality
Security
Security
License
License
Reuse
Reuse

kandi-support Support

  • fastify has a medium active ecosystem.
  • It has 22692 star(s) with 1679 fork(s). There are 281 watchers for this library.
  • There were 10 major release(s) in the last 12 months.
  • There are 55 open issues and 1317 have been closed. On average issues are closed in 77 days. There are 11 open pull requests and 0 closed requests.
  • It has a neutral sentiment in the developer community.
  • The latest version of fastify is v3.28.0
fastify Support
Best in #Runtime Evironment
Average in #Runtime Evironment
fastify Support
Best in #Runtime Evironment
Average in #Runtime Evironment

quality kandi Quality

  • fastify has 0 bugs and 0 code smells.
fastify Quality
Best in #Runtime Evironment
Average in #Runtime Evironment
fastify Quality
Best in #Runtime Evironment
Average in #Runtime Evironment

securitySecurity

  • fastify has no vulnerabilities reported, and its dependent libraries have no vulnerabilities reported.
  • fastify code analysis shows 0 unresolved vulnerabilities.
  • There are 0 security hotspots that need review.
fastify Security
Best in #Runtime Evironment
Average in #Runtime Evironment
fastify Security
Best in #Runtime Evironment
Average in #Runtime Evironment

license License

  • fastify has a Non-SPDX License.
  • Non-SPDX licenses can be open source with a non SPDX compliant license, or non open source licenses, and you need to review them closely before use.
fastify License
Best in #Runtime Evironment
Average in #Runtime Evironment
fastify License
Best in #Runtime Evironment
Average in #Runtime Evironment

buildReuse

  • fastify releases are available to install and integrate.
  • Deployable package is available in npm.
  • Installation instructions, examples and code snippets are available.
fastify Reuse
Best in #Runtime Evironment
Average in #Runtime Evironment
fastify Reuse
Best in #Runtime Evironment
Average in #Runtime Evironment
Top functions reviewed by kandi - BETA

kandi has reviewed fastify and discovered the below as its top functions. This is intended to give you an instant insight into fastify implemented functionality, and help decide if they suit your requirements.

  • Validate the installation parameters
    • This is the two -O router functions .
      • Parses an integer

        Get all kandi verified functions for this library.

        Get all kandi verified functions for this library.

        fastify Key Features

        Highly performant: as far as we know, Fastify is one of the fastest web frameworks in town, depending on the code complexity we can serve up to 76+ thousand requests per second.

        Extendible: Fastify is fully extensible via its hooks, plugins and decorators.

        Schema based: even if it is not mandatory we recommend to use JSON Schema to validate your routes and serialize your outputs, internally Fastify compiles the schema in a highly performant function.

        Logging: logs are extremely important but are costly; we chose the best logger to almost remove this cost, Pino!

        Developer friendly: the framework is built to be very expressive and help the developer in their daily use, without sacrificing performance and security.

        fastify Examples and Code Snippets

        See all related Code Snippets

        Quick start

        copy iconCopydownload iconDownload
        mkdir my-app
        cd my-app
        

        Install

        copy iconCopydownload iconDownload
        npm i fastify@next --save
        

        Example

        copy iconCopydownload iconDownload
        // Require the framework and instantiate it
        
        // ESM
        import Fastify from 'fastify'
        const fastify = Fastify({
          logger: true
        })
        // CommonJs
        const fastify = require('fastify')({
          logger: true
        })
        
        // Declare a route
        fastify.get('/', (request, reply) => {
          reply.send({ hello: 'world' })
        })
        
        // Run the server!
        fastify.listen(3000, (err, address) => {
          if (err) throw err
          // Server is now listening on ${address}
        })
        

        How to end process on specific error in fastify using setErrorHandler?

        copy iconCopydownload iconDownload
        // when there is an async func, the `done` arg must be removed
        const ConnectAndInitDB = async function (fastify, { config, initSqlPath }) {
          await fastify.register(fastifyPostgres, config)
          console.log('DB Connected.')
        
          try {
            await fastify.register(InitDB, { initSqlPath }) 
            console.log('DB Initialized.')
          } catch (error) {
            console.log(`got error`)
            throw error // bubble up the error so fastify server will not start
          }
        }
        

        When push to heroku container - huge amount of data is generated

        copy iconCopydownload iconDownload
        .env
        .github
        node_modules
        

        NestJS: How to customise log messages to include request id and name of the file the log message occurred

        copy iconCopydownload iconDownload
        // main.ts
        
        import { Logger } from 'nestjs-pino';
        
        async function bootstrap() {
        
        const app = await NestFactory.create<NestFastifyApplication>(
            AppModule,
            new FastifyAdapter(),
            { bufferLogs: true }
          );
        
          app.useLogger(app.get(Logger));
          
        }
        bootstrap();
        // app.module.ts
        
        import { LoggerModule } from 'nestjs-pino';
        
        @Module({
          imports: [
            LoggerModule.forRoot({
              pinoHttp: {
                level: process.env.LOG_LEVEL || 'debug',
                redact: ['request.headers.authorization'],
                prettyPrint: {
                  colorize: true,
                  singleLine: true,
                  levelFirst: false,
                  translateTime: "yyyy-MM-dd'T'HH:mm:ss.l'Z'",
                  messageFormat: "{req.headers.x-correlation-id} [{context}] {msg}",
                  ignore: "pid,hostname,context,req,res,responseTime",
                  errorLikeObjectKeys: ['err', 'error']
                }
              }
            }),
          ],
          controllers: [MyController],
        })
        export class AppModule {}
        // my.controller.ts
        import { Controller, Get, Param, Logger } from '@nestjs/common';
        
        @Controller()
        export class MyController {
            private readonly logger: Logger = new Logger(MyController.name);
        
            @Get('/:id')
            async getCustomerDetails(@Headers() headers, @Param('id') id: string): Promise<Customer> {
                this.logger.log(`Accepted incoming request with id: ${id}`);
        
                // Do some processing ....
        
                return customer;
            }
        }
        [2022-11-14T11:03:07.100Z] INFO: 428f0df9-d12b-4fca-9b11-805a13ff41be [MyController] Accepted incoming request with id: 1
        // main.ts
        
        import { Logger } from 'nestjs-pino';
        
        async function bootstrap() {
        
        const app = await NestFactory.create<NestFastifyApplication>(
            AppModule,
            new FastifyAdapter(),
            { bufferLogs: true }
          );
        
          app.useLogger(app.get(Logger));
          
        }
        bootstrap();
        // app.module.ts
        
        import { LoggerModule } from 'nestjs-pino';
        
        @Module({
          imports: [
            LoggerModule.forRoot({
              pinoHttp: {
                level: process.env.LOG_LEVEL || 'debug',
                redact: ['request.headers.authorization'],
                prettyPrint: {
                  colorize: true,
                  singleLine: true,
                  levelFirst: false,
                  translateTime: "yyyy-MM-dd'T'HH:mm:ss.l'Z'",
                  messageFormat: "{req.headers.x-correlation-id} [{context}] {msg}",
                  ignore: "pid,hostname,context,req,res,responseTime",
                  errorLikeObjectKeys: ['err', 'error']
                }
              }
            }),
          ],
          controllers: [MyController],
        })
        export class AppModule {}
        // my.controller.ts
        import { Controller, Get, Param, Logger } from '@nestjs/common';
        
        @Controller()
        export class MyController {
            private readonly logger: Logger = new Logger(MyController.name);
        
            @Get('/:id')
            async getCustomerDetails(@Headers() headers, @Param('id') id: string): Promise<Customer> {
                this.logger.log(`Accepted incoming request with id: ${id}`);
        
                // Do some processing ....
        
                return customer;
            }
        }
        [2022-11-14T11:03:07.100Z] INFO: 428f0df9-d12b-4fca-9b11-805a13ff41be [MyController] Accepted incoming request with id: 1
        // main.ts
        
        import { Logger } from 'nestjs-pino';
        
        async function bootstrap() {
        
        const app = await NestFactory.create<NestFastifyApplication>(
            AppModule,
            new FastifyAdapter(),
            { bufferLogs: true }
          );
        
          app.useLogger(app.get(Logger));
          
        }
        bootstrap();
        // app.module.ts
        
        import { LoggerModule } from 'nestjs-pino';
        
        @Module({
          imports: [
            LoggerModule.forRoot({
              pinoHttp: {
                level: process.env.LOG_LEVEL || 'debug',
                redact: ['request.headers.authorization'],
                prettyPrint: {
                  colorize: true,
                  singleLine: true,
                  levelFirst: false,
                  translateTime: "yyyy-MM-dd'T'HH:mm:ss.l'Z'",
                  messageFormat: "{req.headers.x-correlation-id} [{context}] {msg}",
                  ignore: "pid,hostname,context,req,res,responseTime",
                  errorLikeObjectKeys: ['err', 'error']
                }
              }
            }),
          ],
          controllers: [MyController],
        })
        export class AppModule {}
        // my.controller.ts
        import { Controller, Get, Param, Logger } from '@nestjs/common';
        
        @Controller()
        export class MyController {
            private readonly logger: Logger = new Logger(MyController.name);
        
            @Get('/:id')
            async getCustomerDetails(@Headers() headers, @Param('id') id: string): Promise<Customer> {
                this.logger.log(`Accepted incoming request with id: ${id}`);
        
                // Do some processing ....
        
                return customer;
            }
        }
        [2022-11-14T11:03:07.100Z] INFO: 428f0df9-d12b-4fca-9b11-805a13ff41be [MyController] Accepted incoming request with id: 1
        // main.ts
        
        import { Logger } from 'nestjs-pino';
        
        async function bootstrap() {
        
        const app = await NestFactory.create<NestFastifyApplication>(
            AppModule,
            new FastifyAdapter(),
            { bufferLogs: true }
          );
        
          app.useLogger(app.get(Logger));
          
        }
        bootstrap();
        // app.module.ts
        
        import { LoggerModule } from 'nestjs-pino';
        
        @Module({
          imports: [
            LoggerModule.forRoot({
              pinoHttp: {
                level: process.env.LOG_LEVEL || 'debug',
                redact: ['request.headers.authorization'],
                prettyPrint: {
                  colorize: true,
                  singleLine: true,
                  levelFirst: false,
                  translateTime: "yyyy-MM-dd'T'HH:mm:ss.l'Z'",
                  messageFormat: "{req.headers.x-correlation-id} [{context}] {msg}",
                  ignore: "pid,hostname,context,req,res,responseTime",
                  errorLikeObjectKeys: ['err', 'error']
                }
              }
            }),
          ],
          controllers: [MyController],
        })
        export class AppModule {}
        // my.controller.ts
        import { Controller, Get, Param, Logger } from '@nestjs/common';
        
        @Controller()
        export class MyController {
            private readonly logger: Logger = new Logger(MyController.name);
        
            @Get('/:id')
            async getCustomerDetails(@Headers() headers, @Param('id') id: string): Promise<Customer> {
                this.logger.log(`Accepted incoming request with id: ${id}`);
        
                // Do some processing ....
        
                return customer;
            }
        }
        [2022-11-14T11:03:07.100Z] INFO: 428f0df9-d12b-4fca-9b11-805a13ff41be [MyController] Accepted incoming request with id: 1

        How to access the file path of uploaded files in fastify

        copy iconCopydownload iconDownload
        fastify.register(require("fastify-multipart"), {
          preservePath: true
        });
        

        request.query does not print the query in Fastify (querystring)

        copy iconCopydownload iconDownload
        status: { type: 'object', additionalProperties: true }
        

        pino logger as fastify plugin

        copy iconCopydownload iconDownload
        const decorateLogger = require('my-logger-module')
        
        const applicationConfig = loadAppConfig()
        
        decorateLogger(applicationConfig, options)
        
        const app = Fastify(applicationConfig)
        

        How to add tracking id for each request in fastify?

        copy iconCopydownload iconDownload
        const fastify = require('fastify')({
          logger: true,
          requestIdLogLabel: 'trackingId',
        })
        
        fastify.get('/', async (request, reply) => {
          request.log.info('Custom log message')
          return { hello: 'world' }
        })
        fastify.listen(8080)
        
        
        {"level":30,"trackingId":"req-1","req":{"method":"GET","url":"/","hostname":"localhost:8080","remoteAddress":"127.0.0.1","remotePort":50743},"msg":"incoming request"}
        {"level":30,"trackingId":"req-1","msg":"Custom log message"}
        {"level":30,"trackingId":"req-1","res":{"statusCode":200},"responseTime":3.57566699385643,"msg":"request completed"}
        
        const fastify = require('fastify')({
          logger: true,
          requestIdLogLabel: 'trackingId',
        })
        
        fastify.get('/', async (request, reply) => {
          request.log.info('Custom log message')
          return { hello: 'world' }
        })
        fastify.listen(8080)
        
        
        {"level":30,"trackingId":"req-1","req":{"method":"GET","url":"/","hostname":"localhost:8080","remoteAddress":"127.0.0.1","remotePort":50743},"msg":"incoming request"}
        {"level":30,"trackingId":"req-1","msg":"Custom log message"}
        {"level":30,"trackingId":"req-1","res":{"statusCode":200},"responseTime":3.57566699385643,"msg":"request completed"}
        

        Invalid regular expression - Invalid property name in character class

        copy iconCopydownload iconDownload
        const SAFE_STRING_REPLACE_REGEXP = /[^\p{Script=Latin}\p{Zs}\p{M}\p{Nd}'\s-]/gu;
        // or
        const SAFE_STRING_REPLACE_REGEXP = /[^\p{sc=Latin}\p{Zs}\p{M}\p{Nd}'\s-]/gu;
        
        const SAFE_STRING_REPLACE_REGEXP = /[^\p{Script=Latin}\p{Zs}\p{M}\p{Nd}'\s-]/u;
        console.log("Ącki-Łał русский!!!中国".split(SAFE_STRING_REPLACE_REGEXP).join(""))
        const SAFE_STRING_REPLACE_REGEXP = /[^\p{Script=Latin}\p{Zs}\p{M}\p{Nd}'\s-]/gu;
        // or
        const SAFE_STRING_REPLACE_REGEXP = /[^\p{sc=Latin}\p{Zs}\p{M}\p{Nd}'\s-]/gu;
        
        const SAFE_STRING_REPLACE_REGEXP = /[^\p{Script=Latin}\p{Zs}\p{M}\p{Nd}'\s-]/u;
        console.log("Ącki-Łał русский!!!中国".split(SAFE_STRING_REPLACE_REGEXP).join(""))

        Unable to set cookie in nestjs, TypeError: Cannot set properties of undefined (setting 'color')

        copy iconCopydownload iconDownload
        imports..
        import secureSession from 'fastify-secure-session';
        
        async function bootstrap() {
          const app = await NestFactory.create<NestFastifyApplication>(
            AppModule,
            new FastifyAdapter( )
            );
        
          app.register(secureSession, {
            secret: 'averylogphrasebiggerthanthirtytwochars',
            salt: 'mq9hDxBVDbspDR6n',
          });
        
          lines..
        }
        bootstrap();
        
        imports..
        import * as secureSession from 'fastify-secure-session'
        
        @Controller( 'auth' )
        @MongooseClassSerializerInterceptor( UserDto )
        export class UsersController {
        
            constructor( private usersService: UsersService, private authService: AuthService ) { }
        
            @Get( '/colors/:color' )
            setColor( @Param( 'color' ) color: string, @Session( ) session: secureSession.Session ) {
                console.log( 'check ', session );
                // session.color = color;
                session.set('color', color)
            }
        
            @Get( '/colors' ) 
            getColor( @Session( ) session: secureSession.Session ) {
                console.log( 'get session: ', session );
                // return session.color;
                return session.get( 'color' );
            }
           
        }
        
        imports..
        import secureSession from 'fastify-secure-session';
        
        async function bootstrap() {
          const app = await NestFactory.create<NestFastifyApplication>(
            AppModule,
            new FastifyAdapter( )
            );
        
          app.register(secureSession, {
            secret: 'averylogphrasebiggerthanthirtytwochars',
            salt: 'mq9hDxBVDbspDR6n',
          });
        
          lines..
        }
        bootstrap();
        
        imports..
        import * as secureSession from 'fastify-secure-session'
        
        @Controller( 'auth' )
        @MongooseClassSerializerInterceptor( UserDto )
        export class UsersController {
        
            constructor( private usersService: UsersService, private authService: AuthService ) { }
        
            @Get( '/colors/:color' )
            setColor( @Param( 'color' ) color: string, @Session( ) session: secureSession.Session ) {
                console.log( 'check ', session );
                // session.color = color;
                session.set('color', color)
            }
        
            @Get( '/colors' ) 
            getColor( @Session( ) session: secureSession.Session ) {
                console.log( 'get session: ', session );
                // return session.color;
                return session.get( 'color' );
            }
           
        }
        

        Fastify: avoiding writing boiler plate handler in every routes

        copy iconCopydownload iconDownload
        async function handler(request, reply) {
          reply.from(proxyMap[request.url])
          return reply
        }
        
        const proxyMap = {
          '/api/path1/proxy1': '/api/backend/api1',
          '/api/path2/proxy2': '/api/backend/api2',
        }
        
        Object.keys(proxyMap).forEach((url) => {
          fastify.get(url, { handler })
        })
        

        See all related Code Snippets

        Community Discussions

        Trending Discussions on fastify
        • How to end process on specific error in fastify using setErrorHandler?
        • When push to heroku container - huge amount of data is generated
        • NestJS: How to customise log messages to include request id and name of the file the log message occurred
        • How to access the file path of uploaded files in fastify
        • request.query does not print the query in Fastify (querystring)
        • pino logger as fastify plugin
        • How to add tracking id for each request in fastify?
        • Invalid regular expression - Invalid property name in character class
        • Unable to set cookie in nestjs, TypeError: Cannot set properties of undefined (setting 'color')
        • Fastify: avoiding writing boiler plate handler in every routes
        Trending Discussions on fastify

        QUESTION

        How to end process on specific error in fastify using setErrorHandler?

        Asked 2022-Apr-11 at 07:07

        In my app I'm connecting to a database and then initialize it. I have two custom plugins for that. First plugin connects to DB, and then it registers the second plugin, which initializes the DB (creates tables, domains etc.)

        I want to stop process if an error happens inside those two plugins, since without DB connection and initialization the app won't work.

        In app.ts I have

        const fastify = Fastify({ logger: true });
        
        fastify.register<ConnectAndInitDBConfig>(ConnectAndInitDB, {
          config,
          initSqlPath: 'assets/init.sql',
        });
        

        Here is the first plugin ConnectAndInitDB

        const ConnectAndInitDB: FastifyPluginCallback<ConnectAndInitDBConfig> = (
          fastify,
          { config, initSqlPath },
          done
        ) => {
          fastify.register(fastifyPostgres, config); // this connects to the DB (fastify-postgres NPM package)
          fastify.after(err => {
            if (err) {
              fastify.log.error(err);
              return done(err);
            }
            console.log('DB Connected.');
          });
          fastify.register(InitDB, { initSqlPath }); // this initializes the DB
          fastify.after(err => {
            if (err) {
              fastify.log.error(err);
              return done(err);
            }
            console.log('DB Initialized.');
          });
        
          fastify.setErrorHandler(function errorHandler(error) {
            console.log(`got error`); // this is never called, even if an error happens during initialization of the DB
          });
          done();
        };
        

        Here is the second plugin InitDB

        const InitDB: FastifyPluginCallback<{ initSqlPath: string }> = async (
          fastify,
          { initSqlPath }: { initSqlPath: string },
          done
        ) => {
          try {
            const initSql = await (
              await promisify(readFile)(join(resolve(), initSqlPath))
            ).toString();
            await fastify.pg.pool.query(initSql);
            console.log({ initSql });
          } catch (err: Error | unknown) {
            return done(err as Error);
          }
          done();
        };
        

        When the error happens inside the InitDB plugin, I see it's logged by fastify logger, but I'm not able to catch it inside the setErrorHandler.

        How do I catch any error that happens exactly inside my custom plugins, and let fastify handle all other errors?

        ANSWER

        Answered 2022-Apr-11 at 07:07

        You don't need the errorHandler because it is triggered for HTTP errors, not for the fastify server startup errors.

        It is quite simple to archive your needs:

        // when there is an async func, the `done` arg must be removed
        const ConnectAndInitDB = async function (fastify, { config, initSqlPath }) {
          await fastify.register(fastifyPostgres, config)
          console.log('DB Connected.')
        
          try {
            await fastify.register(InitDB, { initSqlPath }) 
            console.log('DB Initialized.')
          } catch (error) {
            console.log(`got error`)
            throw error // bubble up the error so fastify server will not start
          }
        }
        

        Source https://stackoverflow.com/questions/71816277

        Community Discussions, Code Snippets contain sources that include Stack Exchange Network

        Vulnerabilities

        No vulnerabilities reported

        Install fastify

        Create a folder and make it your current working directory:.
        If installing in an existing project, then Fastify can be installed into the project as a dependency:.

        Support

        Getting StartedGuidesServerRoutesEncapsulationLoggingMiddlewareHooksDecoratorsValidation and SerializationFluent SchemaLifecycleReplyRequestErrorsContent Type ParserPluginsTestingBenchmarkingHow to write a good pluginPlugins GuideHTTP2Long Term SupportTypeScript and types supportServerlessRecommendations

        DOWNLOAD this Library from

        Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
        over 430 million Knowledge Items
        Find more libraries
        Reuse Solution Kits and Libraries Curated by Popular Use Cases
        Explore Kits

        Save this library and start creating your kit

        Share this Page

        share link
        Consider Popular Runtime Evironment Libraries
        Try Top Libraries by fastify
        Compare Runtime Evironment Libraries with Highest Support
        Compare Runtime Evironment Libraries with Highest Quality
        Compare Runtime Evironment Libraries with Highest Security
        Compare Runtime Evironment Libraries with Permissive License
        Compare Runtime Evironment Libraries with Highest Reuse
        Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
        over 430 million Knowledge Items
        Find more libraries
        Reuse Solution Kits and Libraries Curated by Popular Use Cases
        Explore Kits

        Save this library and start creating your kit

        • © 2022 Open Weaver Inc.