Skip to content

Instantly share code, notes, and snippets.

@bcomnes
Created October 10, 2022 15:50
Show Gist options
  • Save bcomnes/021522a0b7ec11e255e5887c315cd890 to your computer and use it in GitHub Desktop.
Save bcomnes/021522a0b7ec11e255e5887c315cd890 to your computer and use it in GitHub Desktop.
Fastify static with private admin section
import fp from 'fastify-plugin'
import path from 'path'
import desm from 'desm'
const __dirname = desm(import.meta.url)
/**
* This plugins adds fastify-static
*
* @see https://github.com/fastify/fastify-static
*/
export default fp(async function (fastify, opts) {
fastify.register(import('@fastify/static'), {
root: path.join(__dirname, '../public'),
prefix: '/',
redirect: true,
maxAge: 600000,
lastModified: fastify.config.ENV !== 'production', // Always showing Tue, 01 Jan 1980 00:00:01 GMT in prod for some reason
allowedPath: (pathName, root, request) => !pathName.startsWith('/admin')
})
fastify.register(async function (fastify, opts) {
fastify.addHook('preHandler', fastify.auth([
fastify.verifyJWT,
fastify.verifyAdmin
], {
relation: 'and'
}))
fastify.register(import('@fastify/static'), {
root: path.join(__dirname, '../public/admin'),
prefix: '/',
redirect: true,
cacheControl: false,
decorateReply: false,
etag: false,
lastModified: false
})
}, { prefix: '/admin' })
}, {
name: 'static',
dependencies: ['compress', 'auth', 'jwt']
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment