Categories
Fastify

Server-Side Development with Fastify — Customize Logging

Fastify is a small Node framework for developing back end web apps.

In this article, we’ll look at how to create back end apps with Fastify.

Customize Logging

We can also customize how responses are logged.

For instance, we can write:

const fastify = require('fastify')({
  logger: {
    prettyPrint: true,
    serializers: {
      res (reply) {
        return {
          statusCode: reply.statusCode
        }
      },
      req (request) {
        return {
          method: request.method,
          url: request.url,
          path: request.path,
          parameters: request.parameters,
          headers: request.headers
        };
      }
    }
  }
});

fastify.get('/', (request, reply) => {
  request.log.info('Some info')
  reply.send({ hello: 'world' })
})

const start = async () => {
  try {
    await fastify.listen(3000, '0.0.0.0')
  } catch (err) {
    fastify.log.error(err)
    process.exit(1)
  }
}
start()

to serialize the response log content with the res method.

And we do the same for the request with the req method.

We set prettyPrint to true to pretty print our output.

We can add a hook to our request to log the request payload by writing:

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

fastify.addHook('preHandler', (req, reply, done) => {
  if (req.body) {
    req.log.info({ body: req.body }, 'parsed body')
  }
  done()
})

fastify.post('/', (request, reply) => {
  reply.send({ hello: 'world' })
})

const start = async () => {
  try {
    await fastify.listen(3000, '0.0.0.0')
  } catch (err) {
    fastify.log.error(err)
    process.exit(1)
  }
}
start()

We get the req.body and put that in the req.log.info call.

Also, we can use the logger outside route handlers.

For instance, we can write:

const log = require('pino')({ level: 'info' })
const fastify = require('fastify')({ logger: log })

log.info('does not have request information')

fastify.get('/', function (request, reply) {
  request.log.info('includes request information, but is the same logger instance as `log`')
  reply.send({ hello: 'world' })
})

const start = async () => {
  try {
    await fastify.listen(3000, '0.0.0.0')
  } catch (err) {
    fastify.log.error(err)
    process.exit(1)
  }
}
start()

We call log.info outside the route handler.

And we call request.log.info inside it.

We can redact log info with the redact property.

For example, we can write:

const split = require('split2')
const stream = split(JSON.parse)

const fastify = require('fastify')({
  logger: {
    stream,
    redact: ['req.headers.authorization'],
    level: 'info',
    serializers: {
      req (request) {
        return {
          method: request.method,
          url: request.url,
          headers: request.headers,
          hostname: request.hostname,
          remoteAddress: request.ip,
          remotePort: request.socket.remotePort
        }
      }
    }
  }
})

fastify.get('/', function (request, reply) {
  reply.send({ hello: 'world' })
})

const start = async () => {
  try {
    await fastify.listen(3000, '0.0.0.0')
  } catch (err) {
    fastify.log.error(err)
    process.exit(1)
  }
}
start()

We add the redact property to add the property paths to skip in ur log.

Now we won’t see the value of req.headers.authorization in our log.

Conclusion

We can customize our logging with Fastify.

Categories
Fastify

Server-Side Development with Fastify — Versioning and Logging

Fastify is a small Node framework for developing back end web apps.

In this article, we’ll look at how to create back end apps with Fastify.

Version

We can set the version to accept with the version property.

For instance, we can write:

const fastify = require('fastify')()

fastify.route({
  method: 'GET',
  url: '/',
  version: '1.2.0',
  handler (request, reply) {
    reply.send({ hello: 'world' })
  }
})
const start = async () => {
  try {
    await fastify.listen(3000, '0.0.0.0')
  } catch (err) {
    fastify.log.error(err)
    process.exit(1)
  }
}
start()

Then our / route will check the Accept-Version header from the request to see if it matches what we have.

If we make a request with Accept-Version set to 1.x , 1.2.0 or 1.2.x , then we see:

{ hello: 'world' }

in the response.

Otherwise, we get 404.

Logging

Logging is disabled by default.

We can enable logging by setting the logger property.

For instance, we can write:

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

fastify.get('/', (request, reply) => {
  request.log.info('Some info')
  reply.send({ hello: 'world' })
})

const start = async () => {
  try {
    await fastify.listen(3000, '0.0.0.0')
  } catch (err) {
    fastify.log.error(err)
    process.exit(1)
  }
}
start()

to enable logging with logger set to true .

Then we call request.log.info to log something to the console.

We should see something like.

{"level":30,"time":1604268389762,"pid":737,"hostname":"9cc07d2eed9d","reqId":2,"msg":"Some info"}

logged.

We can also pass some options to the logger.

For example, we can write:

const fastify = require('fastify')({
  logger: {
    level: 'info',
    file: './log.txt'
  }
})

fastify.get('/', (request, reply) => {
  request.log.info('Some info')
  reply.send({ hello: 'world' })
})

const start = async () => {
  try {
    await fastify.listen(3000, '0.0.0.0')
  } catch (err) {
    fastify.log.error(err)
    process.exit(1)
  }
}
start()

Then we log the output to log.txt .

We can pass a custom stream to the Pino instance.

To do this, we write:

const split = require('split2')
const stream = split(JSON.parse)

const fastify = require('fastify')({
  logger: {
    level: 'info',
    stream: stream
  }
})
fastify.get('/', (request, reply) => {
  request.log.info('Some info')
  reply.send({ hello: 'world' })
})

const start = async () => {
  try {
    await fastify.listen(3000, '0.0.0.0')
  } catch (err) {
    fastify.log.error(err)
    process.exit(1)
  }
}
start()

to pass in a custom stream that’s created with:

const stream = split(JSON.parse)

Also, we can customize what’s logged with the serializers property.

We can write:

const fastify = require('fastify')({
  logger: {
    serializers: {
      req (request) {
        return { url: request.url }
      }
    }
  }
})

fastify.get('/', (request, reply) => {
  request.log.info('Some info')
  reply.send({ hello: 'world' })
})

const start = async () => {
  try {
    await fastify.listen(3000, '0.0.0.0')
  } catch (err) {
    fastify.log.error(err)
    process.exit(1)
  }
}
start()

to add the serializers property which has the req function to return an object with the data we want to record from the request.

Conclusion

We can set the version of the API and adding logging with Fastify.

Categories
Fastify

Server-Side Development with Fastify — Custom Logging and Route Config

Fastify is a small Node framework for developing back end web apps.

In this article, we’ll look at how to create back end apps with Fastify.

Custom Log Level

We can change the log level of our Fastify app.

For instance, we can write:

index.js

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

fastify.register(require('./routes/v1/users'), { prefix: '/v1' })
fastify.register(require('./routes/v2/users'), { prefix: '/v2' })

const start = async () => {
  try {
    await fastify.listen(3000, '0.0.0.0')
  } catch (err) {
    fastify.log.error(err)
    process.exit(1)
  }
}
start()

routes/v1/users.js

module.exports = function (fastify, opts, done) {
  fastify.get('/user', async () => 'v1')
  done()
}

routes/v2/user.js

module.exports = function (fastify, opts, done) {
  fastify.get('/user', async () => 'v2')
  done()
}

We set logger to true to enable logging.

We can also set the logging levels for individual routes.

For instance, we can write:

const fastify = require('fastify')()

fastify.get('/', { logLevel: 'warn' }, (request, reply) => {
  reply.send({ hello: 'world' })
})

const start = async () => {
  try {
    await fastify.listen(3000, '0.0.0.0')
  } catch (err) {
    fastify.log.error(err)
    process.exit(1)
  }
}
start()

We set the logLevel to 'warn' on the / route.

Custom Log Serializer

We can customize the log serializer.

For instance, we can write:

const fastify = require('fastify')({
  logger: {
    level: 'info',
    serializers: {
      user (req) {
        return {
          method: req.method,
          url: req.url,
          headers: req.headers,
          hostname: req.hostname,
          remoteAddress: req.ip,
          remotePort: req.socket.remotePort
        }
      }
    }
  }
})

fastify.register(context1, {
  logSerializers: {
    user: value => `My serializer father - ${value}`
  }
})

async function context1 (fastify, opts) {
  fastify.get('/', (req, reply) => {
    req.log.info({ user: 'call father serializer', key: 'another key' })
    reply.send({})
  })
}
const start = async () => {
  try {
    await fastify.listen(3000, '0.0.0.0')
  } catch (err) {
    fastify.log.error(err)
    process.exit(1)
  }
}
start()

to add the logSerializers property.

We configure the logger when we call the Fastify factory function on the first line.

We set the level to set the log level.

serializers has an object with the user function that returns the info from the request.

We return the request method, URL, headers, hostname, IP, and remote port respectively.

Then when we make the request, we see the output in the console.

Route Config

We can pass in a config object when we define our route.

For instance, we can write:

const fastify = require('fastify')()

function handler (req, reply) {
  reply.send(reply.context.config.output)
}

fastify.get('/en', { config: { output: 'hello world!' } }, handler)
fastify.get('/fr', { config: { output: 'bonjour' } }, handler)

const start = async () => {
  try {
    await fastify.listen(3000, '0.0.0.0')
  } catch (err) {
    fastify.log.error(err)
    process.exit(1)
  }
}
start()

We pass in an object with the config property in the 2nd argument.

Then we can get that value from the reply.context property.

Conclusion

We can set the custom logging and set route config with Fastify.

Categories
Fastify

Server-Side Development with Fastify — Async and Await and Route Prefixes

Fastify is a small Node framework for developing back end web apps.

In this article, we’ll look at how to create back end apps with Fastify.

Async Await

We can use async and await in our route handlers.

For example, we can write:

const fastify = require('fastify')()

const getData = () => Promise.resolve('foo')
const processData = (data) => Promise.resolve(data)

const opts = {
  schema: {
    response: {
      200: {
        type: 'string'
      }
    }
  }
}

fastify.get('/', opts, async function (request, reply) {
  const data = await getData()
  const processed = await processData(data)
  return processed
})

const start = async () => {
  try {
    await fastify.listen(3000, '0.0.0.0')
  } catch (err) {
    fastify.log.error(err)
    process.exit(1)
  }
}
start()

We use an async function as the route handler.

then we can use await in the handler to run promises.

We an also use reply.send to send back the data.

For example, we can write:

const fastify = require('fastify')()

const getData = () => Promise.resolve('foo')
const processData = (data) => Promise.resolve(data)

const opts = {
  schema: {
    response: {
      200: {
        type: 'string'
      }
    }
  }
}

fastify.get('/', opts, async function (request, reply) {
  const data = await getData()
  const processed = await processData(data)
  reply.send(processed)
})

const start = async () => {
  try {
    await fastify.listen(3000, '0.0.0.0')
  } catch (err) {
    fastify.log.error(err)
    process.exit(1)
  }
}
start()

to call reply.send to send back the response.

We can also await our reply if we’re calling reply.send in an async callback.

For example, we can write:

const fastify = require('fastify')()

const getData = () => Promise.resolve('foo')
const processData = (data) => Promise.resolve(data)

const opts = {
  schema: {
    response: {
      200: {
        type: 'object',
        properties: {
          hello: {
            type: 'string'
          }
        }
      }
    }
  }
}

fastify.get('/', opts, async function (request, reply) {
  setImmediate(() => {
    reply.send({ hello: 'world' })
  })
  await reply
})

const start = async () => {
  try {
    await fastify.listen(3000, '0.0.0.0')
  } catch (err) {
    fastify.log.error(err)
    process.exit(1)
  }
}
start()

to await our reply since we called reply.send in the setImmediate callback.

When using both return value and reply.send(value) at the same time, the first one that happens takes precedence.

If we use async and await with reply.send , then we shouldn’t return any value.

And if we’re using async and await with promises, then we should return the value and don’t use reply.send or return undefined .

Route Prefixing

We can add prefixes to routes.

For example, we can write:

index.js

const fastify = require('fastify')()

fastify.register(require('./routes/v1/users'), { prefix: '/v1' })
fastify.register(require('./routes/v2/users'), { prefix: '/v2' })

const start = async () => {
  try {
    await fastify.listen(3000, '0.0.0.0')
  } catch (err) {
    fastify.log.error(err)
    process.exit(1)
  }
}
start()

routes/v1/users.js

module.exports = function (fastify, opts, done) {
  fastify.get('/user', async () => 'v1')
  done()
}

routes/v2/users.js

module.exports = function (fastify, opts, done) {
  fastify.get('/user', async () => 'v2')
  done()
}

Then when we go to /v1/user, we see v1 .

And when we go to /v2/user, we see v2 .

Conclusion

We can add async functions as route handlers.

And we can add route prefixes with Fastify.

Categories
Fastify

Server-Side Development with Fastify — Route Declarations

Fastify is a small Node framework for developing back end web apps.

In this article, we’ll look at how to create back end apps with Fastify.

Route Declaration Shorthand

Fastify comes with shorthand methods to declare routes.

The methods include:

  • fastify.get(path, [options], handler)
  • fastify.head(path, [options], handler)
  • fastify.post(path, [options], handler)
  • fastify.put(path, [options], handler)
  • fastify.delete(path, [options], handler)
  • fastify.options(path, [options], handler)
  • fastify.patch(path, [options], handler)

For example, we can write:

const fastify = require('fastify')()

const opts = {
  schema: {
    response: {
      200: {
        type: 'object',
        properties: {
          hello: { type: 'string' }
        }
      }
    }
  }
}
fastify.get('/', opts, (request, reply) => {
  reply.send({ hello: 'world' })
})

const start = async () => {
  try {
    await fastify.listen(3000, '0.0.0.0')
  } catch (err) {
    fastify.log.error(err)
    process.exit(1)
  }
}
start()

We create the opts to set the response schema.

Then we pass that into get method as the 2nd argument of it.

We can also write:

const fastify = require('fastify')()

const opts = {
  schema: {
    response: {
      200: {
        type: 'object',
        properties: {
          hello: { type: 'string' }
        }
      }
    }
  },
  handler: function (request, reply) {
    reply.send({ hello: 'world' })
  }
}
fastify.get('/', opts)

const start = async () => {
  try {
    await fastify.listen(3000, '0.0.0.0')
  } catch (err) {
    fastify.log.error(err)
    process.exit(1)
  }
}
start()

to put the handler method in the opts object instead of passing it into the 3rd argument.

Url Building

Fastify supports both static and dynamic URLs.

For example, we can register a parametric path by writing:

const fastify = require('fastify')()

fastify.get('/example/:userId', (request, reply) => {
  reply.send('example')
})
fastify.get('/example/:userId/:secretToken', (request, reply) => {
  reply.send('example')
})
fastify.get('/example/*', (request, reply) => {
  reply.send('example')
})

const start = async () => {
  try {
    await fastify.listen(3000, '0.0.0.0')
  } catch (err) {
    fastify.log.error(err)
    process.exit(1)
  }
}
start()

to add the routes.

:userId and :secretToken are URL parameters.

And * is a wildcard character.

Also, we can use regex to match URL route patterns.

For example, we can write:

const fastify = require('fastify')()

fastify.get('/example/:file(^d+).png', (request, reply) => {
  reply.send('example')
})

const start = async () => {
  try {
    await fastify.listen(3000, '0.0.0.0')
  } catch (err) {
    fastify.log.error(err)
    process.exit(1)
  }
}
start()

We match the URL pattern with the (^d+) pattern.

So when we go to /example/1.png , we see the response returned.

We can define more than one route parameter with the slashes.

For instance, we can write:

const fastify = require('fastify')()

fastify.get('/example/near/:lat-:lng/radius/:r', (request, reply) => {
  reply.send('example')
})

const start = async () => {
  try {
    await fastify.listen(3000, '0.0.0.0')
  } catch (err) {
    fastify.log.error(err)
    process.exit(1)
  }
}
start()

to add the :lat-lng and :r route parameters.

And we can do the same with regex:

const fastify = require('fastify')()

fastify.get('/example/at/:hour(^d{2})h:minute(^d{2})m', (request, reply) => {
  reply.send('example')
})

const start = async () => {
  try {
    await fastify.listen(3000, '0.0.0.0')
  } catch (err) {
    fastify.log.error(err)
    process.exit(1)
  }
}
start()

Conclusion

We can declare routes with various match patterns with Fastify.