With the fastify-basic-auth library, we can add basic authentication to our Fastify app quickly.
In this article, we’ll look at how to use the library to add authentication to our Fastify app.
Installation
We can install the package by running:
npm i fastify-basic-auth
Adding Basic Auth
We can add basic auth to our Fastify app by writing some code.
For example, we can write:
const fastify = require('fastify')({
logger: true
})
const authenticate = {realm: 'Westeros'}
fastify.register(require('fastify-basic-auth'), { validate, authenticate })
function validate (username, password, req, reply, done) {
if (username === 'foo' && password === 'bar') {
done()
} else {
done(new Error('invalid user'))
}
}
fastify.after(() => {
fastify.addHook('onRequest', fastify.basicAuth)
fastify.get('/', (req, reply) => {
reply.send({ hello: 'world' })
})
})
fastify.listen(3000, '0.0.0.0', function (err, address) {
if (err) {
fastify.log.error(err)
process.exit(1)
}
fastify.log.info(`server listening on ${address}`)
})
We register the fastify-basic-auth
plugin with validate
and authenticate
.
validate
is a function to validate the username and password.
authenticate
is an object to set the realm.
To add basic auth, we called addHook
to add a hook that checks the username and password with validate
on each request.
Any routes that are registered in the after
hook have protection with basic auth.
The validate
function can be async.
For example, we can write:
const fastify = require('fastify')({
logger: true
})
const authenticate = {realm: 'Westeros'}
fastify.register(require('fastify-basic-auth'), { validate, authenticate })
async function validate (username, password, req, reply) {
if (username !== 'foo' || password !== 'bar') {
return new Error('invalid user')
}
}
fastify.after(() => {
fastify.addHook('onRequest', fastify.basicAuth)
fastify.get('/', (req, reply) => {
reply.send({ hello: 'world' })
})
})
fastify.listen(3000, '0.0.0.0', function (err, address) {
if (err) {
fastify.log.error(err)
process.exit(1)
}
fastify.log.info(`server listening on ${address}`)
})
If validate
is async, then we don’t need to call done
.
Also, we can use it with the onRequest
property:
const fastify = require('fastify')({
logger: true
})
const authenticate = { realm: 'Westeros' }
fastify.register(require('fastify-basic-auth'), { validate, authenticate })
async function validate (username, password, req, reply) {
if (username !== 'foo' || password !== 'bar') {
return new Error('invalid user')
}
}
fastify.after(() => {
fastify.route({
method: 'GET',
url: '/',
onRequest: fastify.basicAuth,
handler: async (req, reply) => {
return { hello: 'world' }
}
})
})
fastify.listen(3000, '0.0.0.0', function (err, address) {
if (err) {
fastify.log.error(err)
process.exit(1)
}
fastify.log.info(`server listening on ${address}`)
})
We set fastify.basicAuth
as the value of onRequest
to add basic auth to our GET /
route.
Also, we can use it with fastify-auth
:
const fastify = require('fastify')({
logger: true
})
const authenticate = {realm: 'Westeros'}
fastify.register(require('fastify-auth'))
fastify.register(require('fastify-basic-auth'), { validate, authenticate })
async function validate (username, password, req, reply) {
if (username !== 'foo' || password !== 'bar') {
return new Error('invalid user')
}
}
fastify.after(() => {
fastify.addHook('preHandler', fastify.auth([fastify.basicAuth]))
fastify.route({
method: 'GET',
url: '/',
onRequest: fastify.auth([fastify.basicAuth]),
handler: async (req, reply) => {
return { hello: 'world' }
}
})
})
fastify.listen(3000, '0.0.0.0', function (err, address) {
if (err) {
fastify.log.error(err)
process.exit(1)
}
fastify.log.info(`server listening on ${address}`)
})
We register the basic auth handler in the adfter
hook and in the onRequest
property of the GET /
route.
Conclusion
The fastify-basic-auth library lets us add basic auth to our Fastify app with a few lines of code.