@@ -10,6 +10,9 @@ import {
1010 RawReplyDefaultExpression ,
1111 RawRequestDefaultExpression ,
1212 RawServerDefault ,
13+ FastifyReply ,
14+ FastifyRequest ,
15+ RouteOptions ,
1316} from "fastify" ;
1417import fastifyMetrics from "fastify-metrics" ;
1518import * as path from "path" ;
@@ -23,6 +26,7 @@ export type AppOptions = {
2326 // MongoDB URI (Optional)
2427 // mongoUri: string;
2528 lokiHost ?: string ;
29+ prometheusKey ?: string ;
2630} & FastifyServerOptions &
2731 Partial < AutoloadPluginOptions > &
2832 AuthPluginOptions ;
@@ -52,6 +56,7 @@ const options: AppOptions = {
5256 authDiscoveryURL : getOption ( "AUTH_DISCOVERY_URL" ) ! ,
5357 authClientID : getOption ( "AUTH_CLIENT_ID" ) ! ,
5458 lokiHost : getOption ( "LOKI_HOST" , false ) ,
59+ prometheusKey : getOption ( "PROMETHEUS_KEY" , false ) ,
5560 authSkip : ( ( ) => {
5661 const opt = getOption ( "AUTH_SKIP" , false ) ;
5762 if ( opt !== undefined ) {
@@ -69,7 +74,7 @@ if (options.lokiHost) {
6974 target : "pino-loki" ,
7075 options : {
7176 batching : true ,
72- interval : 5 ,
77+ interval : 5 , // Logs are sent every 5 seconds, default.
7378 host : options . lokiHost ,
7479 labels : { application : packageJson . name } ,
7580 } ,
@@ -102,9 +107,26 @@ const app: FastifyPluginAsync<AppOptions> = async (
102107 } ) ;
103108
104109 // Register Metrics
110+ const metricsEndpoint : RouteOptions | string | null = opts . prometheusKey
111+ ? {
112+ url : "/metrics" ,
113+ method : "GET" ,
114+ handler : async ( ) => { } , // Overridden by fastify-metrics
115+ onRequest : async ( request : FastifyRequest , reply : FastifyReply ) => {
116+ if (
117+ request . headers . authorization !== `Bearer ${ opts . prometheusKey } `
118+ ) {
119+ reply . code ( 401 ) . send ( "Unauthorized" ) ;
120+ return reply ;
121+ }
122+ } ,
123+ }
124+ : "/metrics" ;
125+
105126 await fastify . register ( fastifyMetrics . default , {
106- endpoint : "/metrics" ,
127+ endpoint : metricsEndpoint ,
107128 defaultMetrics : { enabled : true } ,
129+ clearRegisterOnInit : true ,
108130 } ) ;
109131
110132 // Register Swagger & Swagger UI & Scalar
0 commit comments