Created
October 10, 2022 15:50
-
-
Save bcomnes/021522a0b7ec11e255e5887c315cd890 to your computer and use it in GitHub Desktop.
Fastify static with private admin section
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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