Opinionated set of fastify plugins, commonly used in Lokalise
npm install @lokalise/fastify-extrasReusable plugins for Fastify.
- Dependency Management
- Plugins
- RequestContext Provider Plugin
- Public Healthcheck Plugin
- Common Healthcheck Plugin
- Common Sync Healthcheck Plugin
- Split IO Plugin
- BugSnag Plugin
- Metrics Plugin
- Bull MQ Metrics Plugin
- NewRelic Transaction Manager Plugin
- OpenTelemetry Transaction Manager Plugin
- UnhandledException Plugin
The following needs to be taken into consideration when adding new runtime dependency for the fastify-extras package:
- If dependency is an implementation detail, and end consumer is not expected to import and use the dependency directly, it should be a dependency;
- If dependency needs to be imported and used by consumer directly for it to function properly, it should be a peerDependency.
- @bugsnag/js;
- @splitsoftware/splitio;
- fastify-metrics;
- fastify-plugin;
- tslib.
- @fastify/jwt;
- @opentelemetry/api;
- fastify;
- newrelic;
- pino;
- bullmq;
Plugin to:
- extend existing FastifyRequest with request context by setting the following:
- logger, a child logger of app.log, with prepopulated properties:
- x-request-id: the request ID
- api-endpoint: the route URL pattern (e.g., /, /:userId)
- api-method: the HTTP method (e.g., GET, POST)
- api-endpoint-param-{paramName}: for each route parameter (e.g., api-endpoint-param-userId for :userId parameter)
- reqId, the request-id
No options are required to register the plugin.
The getRequestIdFastifyAppConfig() method is exported and returns:
- genReqId, a function for generating the request-id;
- requestIdHeader, the header name used to set the request-id.
Which can be passed to Fastify during instantiation.
The getFastifyAppLoggingConfig(appLogLevel, requestLoggingLevels?) method is exported and returns Fastify configuration for request logging. It accepts:
- appLogLevel, the application log level from your app configuration;
- requestLoggingLevels (optional), an array of log levels that should enable request logging. Defaults to ['debug', 'trace', 'info'].
This method returns a disableRequestLogging configuration that:
- Enables request logging only when the app log level is in requestLoggingLevels;
- Automatically skips logging for service utility endpoints (/, /health, /ready, /live, /metrics).
Example usage:
``typescript
import { getFastifyAppLoggingConfig } from '@lokalise/fastify-extras'
const app = fastify({
...getFastifyAppLoggingConfig(appConfig.logLevel),
})
`
Plugin to monitor app status through public healthcheck.
Add the plugin to your Fastify instance by registering it with the following options:
- healthChecks, a list of promises with healthcheck in the callback;responsePayload
- (optional), the response payload that the public healthcheck should return. If no response payload is provided, the default response is:`
json`
{ "heartbeat": "HEALTHY" }
Your Fastify app will reply with the status of the app when hitting the GET / route.
Plugin to monitor app status through public and private healthchecks using asynchronous checks.
Add the plugin to your Fastify instance by registering it with the following options:
- healthChecks, a list of promises with healthcheck in the callback;responsePayload
- (optional), the response payload that the healthcheck should return. If no response payload is provided, the default response is:`
json`
{ "heartbeat": "HEALTHY", "checks": {} }
Your Fastify app will reply with the status of the app when hitting the GET / public route with aggregated heartbeat from healthchecks provided, example:`json`
{
"heartbeat": "HEALTHY"
}
Your Fastify app will reply with the status of the app when hitting the GET /health private route with detailed results from healthchecks provided, example:`json`
{
"heartbeat": "PARTIALLY_HEALTHY",
"checks": {
"check1": "HEALTHY",
"check2": "HEALTHY",
"check3": "FAIL"
}
}
Plugin to monitor app status through public and private healthchecks using synchronous checks. This plugin is recommended when you have healthchecks that run synchronously or are executed in the background, as it provides better performance for such use cases.
Add the plugin to your Fastify instance by registering it with the following options:
- healthChecks, an array of synchronous healthcheck objects, each containing:name
- , the identifier for the healthcheck;isMandatory
- , boolean indicating if this healthcheck is critical for service health;checker
- , a synchronous function that returns null on success or an Error on failure;responsePayload
- (optional), the response payload that the healthcheck should return;logLevel
- (optional), the log level for the healthcheck routes ('fatal' | 'error' | 'warn' | 'info' | 'debug' | 'trace' | 'silent'), defaults to 'info';infoProviders
- (optional), an array of info providers to include additional metadata in the /health response;isRootRouteEnabled
- (optional), whether to enable the public / route, defaults to true.
Example usage:
`typescript
import { commonSyncHealthcheckPlugin } from '@lokalise/fastify-extras'
app.register(commonSyncHealthcheckPlugin, {
healthChecks: [
{
name: 'database',
isMandatory: true,
checker: (app) => {
// Synchronous check - returns null if healthy, Error if not
return isDatabaseConnected() ? null : new Error('Database disconnected')
}
},
{
name: 'cache',
isMandatory: false, // Optional dependency
checker: (app) => {
return isCacheAvailable() ? null : new Error('Cache unavailable')
}
}
]
})
`
The plugin exposes the same routes as the async Common Healthcheck Plugin:
- GET / - Public route returning aggregated health statusGET /health
- - Private route with detailed healthcheck results
The key differences from the async version:
- Uses synchronous healthcheck functions instead of promises
- Better suited for checks that are already running in the background or are inherently synchronous
- Supports mandatory vs optional healthchecks (optional failures result in PARTIALLY_HEALTHY status)
Plugin to monitor app startup status, doing potentially more expensive checks than what is reasonable through periodic healthchecks.
Add the plugin to your Fastify instance by registering it with the following options:
- healthChecks, a list of asynchronous healthchecks to run at the app startup;resultsLogLevel
- , at what log level to report healthcheck results - default is INFO;
This is the structure of the log:
`json`
{
"heartbeat": "PARTIALLY_HEALTHY",
"checks": {
"check1": "HEALTHY",
"check2": "HEALTHY",
"check3": "FAIL"
}
}
In case a non-optional healthcheck fails, an application startup will throw an error. In order to ensure that the error is thrown correctly, make sure to await the app startup:
`ts`
const app = fastify()
await app.register(startupHealthcheckPlugin, opts)
await app.ready()
Plugin to handle feature flags in Split IO.
Add the plugin to your Fastify instance by registering it with the following options:
- isEnabled, if true the plugin will connect to Split IO using the provided apiKey and store data in memory with background syncing;apiKey
- , your SDK key;debugMode
- ;localhostFilePath
- (optional), used to utilize the SDK in localhost mode. It corresponds to the full path to a file with the mapping of feature flag name to treatment. apiKey will be automatically replaced with localhost if localhostFilePath is provided.
The plugin decorates your Fastify instance with a SplitIOFeatureManager, which you can inject and use to leverage the following methods:
- init(), returns a promise that resolves once the SDK has finished loading. It's called automatically when registering the plugin;getTreatment()
- , returns the proper treatment based on the feature flag name and the key in input. Expected parameters are:
- key, the ID of the user/account/etc. you're trying to evaluate a treatment for;splitName
- , the Split IO feature flag name;attributes
- (optional), a set of Attributes used in evaluation to further decide whether to show the on or off treatment;
> _NOTE:_ If isEnabled is false, getTreatement() will return control to signal disabled treatment.
- getTreatmentWithConfig(), used to leverage dynamic configurations with your treatment. It accepts the same parameters as getTreatment(), but the response structure is as follows:`
ts`
type TreatmentResult = {
treatment: string
config: string | null
}
isEnabled
> _NOTE:_ If is false, getTreatementWithConfig() will return control as treatment and null as config to signal disabled treatment.track()
- , used to record any actions your customers perform. Returns a boolean to indicate whether or not the SDK was able to successfully queue the event. Expected parameters are:key
- , the ID of the user/account/etc. you're trying to evaluate a treatment for;trafficType
- , the traffic type of the key;eventType
- , the event type that this event should correspond to;value
- (optional), the value to be used in creating the metric;properties
- (optional), an object of key value pairs that represent the properties to be used to filter your metrics;shutdown()
- , gracefully shuts down the client.
More info about Split IO can be checked here.
Plugin to report errors to BugSnag.
Add the plugin to your Fastify instance by registering it with the following options:
- isEnabled;bugsnag
- , a set of customizable xonfiguration options.
Once the plugin has been added to your Fastify instance and loaded, errors will be reported to BugSnag.
Plugin to expose Prometheus metrics.
Add the plugin to your Fastify instance by registering it with the following options:
- loggerOptions, used to configure the internal logger instance. It can be a boolean or a set of Pino options. By default it is set to false and the logger is disabled;disablePrometheusRequestLogging
- (optional). By default Fastify will issue an info level log message when a request is received and when the response for that request has been sent. By setting this option to true, these log messages will be disabled. Defaults to true;bindAddress
- (optional). By default, the server will listen on the address(es) resolved by localhost when no specific host is provided. See the possible values for host when targeting localhost here;errorObjectResolver
- , a resolver method that, given an err and optionally a correlationID, it will log the error if something goes wrong.
The plugin exposes a GET /metrics route in your Fastify app to retrieve Prometheus metrics. If something goes wrong while starting the Prometheus metrics server, an Error is thrown. Otherwise, a success message is displayed when the plugin has been loaded.
#### PrometheusCounterTransactionManager
PrometheusCounterTransactionManager is an implementation of TransactionObservabilityManager that uses Prometheus /metrics
counters to track the number of started, failed, and successful transactions. The results are automatically added to
the endpoint exposed by the metrics plugin.
Plugin to auto-discover BullMQ queues which can regularly collect metrics for them and expose via fastify-metrics global Prometheus registry. If used together with metricsPlugin, it will show these metrics on GET /metrics route.
This plugin depends on the following peer-installed packages:
- bullmqioredis
-
Add the plugin to your Fastify instance by registering it with the following possible options:
- redisConfigs, Redis configurations used for BullMQ. Plugin uses them to discover the queues.bullMqPrefix
- (optional, default: bull). The prefix used by BullMQ to store the queues in Redis;metricsPrefix
- (optional, default: bullmq). The prefix for the metrics in Prometheus;queueDiscoverer
- (optional, default: BackgroundJobsBasedQueueDiscoverer). The queue discoverer to use. The default one relies on the logic implemented by @lokalise/background-jobs-common where queue names are registered by the background job processors; If you are not using @lokalise/background-jobs-common, you can use your own queue discoverer by instantiating a RedisBasedQueueDiscoverer or implementing a QueueDiscoverer interface;excludedQueues
- (optional, default: []). An array of queue names to exclude from metrics collection;histogramBuckets
- (optional, default: [20, 50, 150, 400, 1000, 3000, 8000, 22000, 60000, 150000]). Buckets for the histogram metrics (such as job completion or overall processing time).collectionOptions
- (optional, default: { type: 'interval', intervalInMs: 5000 }). Allows to configure how metrics are collected. Supports the following properties:type
- . Can be either interval or manual.interval
- With type, plugin automatically loops and updates metrics at the specified interval.manual
- With type, you need to call app.bullMqMetrics.collect() to update the metrics; that allows you to build your own logic for scheduling the updates.intervalInMs
- (only for type: 'interval'). The interval in milliseconds at which the metrics are collected;
This plugin exposes bullMqMetrics.collect() method on the Fastify instance to manually trigger the metrics collection.
If something goes wrong while starting the BullMQ metrics plugin, an Error is thrown.
Plugin to create custom NewRelic spans for background jobs.
Add the plugin to your Fastify instance by registering it with the following options:
- isEnabled.
The plugin decorates your Fastify instance with a NewRelicTransactionManager, which you can inject and use to leverage the following methods:
- start(), which takes a jobName, and starts a background transaction with the provided name;stop()
- , which takes a jobId, and ends the background transaction referenced by the ID;addCustomAttribute()
- , which takes attrName and attrValue and adds the custom attribute to the current transaction. attrValue can be a string, a number, or a boolean.addCustomAttributes()
- , which passes atts map of the custom attributes to the current transaction. _uniqueTransactionKey argument is not used (because New Relic doesn't support setting custom attributes directly on the transaction handle), any string can be passed.
Plugin to create custom OpenTelemetry spans for background jobs. This is an alternative to the NewRelic Transaction Manager Plugin for applications using OpenTelemetry for observability.
Add the plugin to your Fastify instance by registering it with the following options:
- isEnabled, if true the plugin will create spans using OpenTelemetry;tracerName
- (optional), the instrumentation scope name for the tracer. This identifies the instrumentation library, not the service. For service identification, configure it via OpenTelemetry SDK resource attributes (e.g., OTEL_SERVICE_NAME environment variable). Defaults to 'unknown-tracer';tracerVersion
- (optional), the instrumentation scope version for the tracer. Defaults to '1.0.0';maxConcurrentSpans
- (optional), maximum number of concurrent spans to track. When this limit is reached, the oldest spans will be evicted and automatically ended to prevent leaks. Defaults to 2000.
The plugin decorates your Fastify instance with an OpenTelemetryTransactionManager, which implements the TransactionObservabilityManager interface from @lokalise/node-core. You can inject and use the following methods:
- start(transactionName, uniqueTransactionKey), starts a background span with the provided name and stores it by the unique key;startWithGroup(transactionName, uniqueTransactionKey, transactionGroup)
- , starts a background span with an additional transaction.group attribute;stop(uniqueTransactionKey, wasSuccessful?)
- , ends the span referenced by the unique key. Sets status to OK if successful (default), or ERROR if not;addCustomAttribute(attrName, attrValue)
- , adds a custom attribute to the currently active span. attrValue can be a string, number, or boolean;addCustomAttributes(uniqueTransactionKey, atts)
- , adds multiple custom attributes to the span identified by the unique key;setUserID(userId)
- , sets the enduser.id attribute on the active span;setControllerName(name, action)
- , sets code.namespace and code.function attributes on the active span.
Additional OpenTelemetry-specific methods:
- getSpan(uniqueTransactionKey), returns the span for advanced manipulation, or null if not found;getTracer()
- , returns the underlying OpenTelemetry tracer;runInSpanContext(uniqueTransactionKey, fn)
- , executes a function within the context of a specific span, useful for automatic parent-child span linking.
Example usage:
`typescript
import { openTelemetryTransactionManagerPlugin } from '@lokalise/fastify-extras'
// Register the plugin
await app.register(openTelemetryTransactionManagerPlugin, {
isEnabled: true,
tracerName: 'my-instrumentation',
tracerVersion: '1.0.0',
// maxConcurrentSpans: 2000, // optional
})
// Use in your application
const manager = app.openTelemetryTransactionManager
// Start a transaction
manager.start('process-email-job', 'job-123')
// Add custom attributes
manager.addCustomAttributes('job-123', {
jobType: 'email',
recipient: 'user@example.com',
})
// Execute nested operations within the span context
manager.runInSpanContext('job-123', () => {
// Child spans created here will be linked to the parent
doSomeWork()
})
// End the transaction
manager.stop('job-123', true) // true = successful
`
> Note: This plugin requires @opentelemetry/api as a peer dependency. Make sure your application has OpenTelemetry configured with appropriate exporters (e.g., OTLP exporter) to send traces to your observability backend.
This plugin facilitates the transmission of events to Amplitude.
To add this plugin to your Fastify instance, register it with the following configurations:
- isEnabled: A flag utilized to activate or de-activate the plugin.apiKey
- (optional): This refers to the Amplitude API key which can be procured from your respective Amplitude project.options
- (optional): To configure Amplitude, please refer to this documentation.apiUsageTracking
- (optional): You can use this callback to generate an event that will automatically be sent for tracking API usage. Non-specification of this feature will lead to disabling of API tracking.plugins
- (optional): This feature allows you to expand the plugin's functionality, from altering event properties to relaying to third-party APIs. To learn more, visit this link.
The plugin decorates your Fastify instance with a Amplitude, which you can inject and use the track method on it to send events whenever you need
> 📘 To ensure optimal functionality with this plugin, you may need to incorporate Amplitude types into your development dependencies.
>
> ``
> "@amplitude/analytics-types": "*"
>
Related utilities:
- AmplitudeAdapter - A type-safe wrapper that validates events using Zod schemas before sending them to AmplitudeFakeAmplitude
- - A utility class for testing environments that doesn't send events to Amplitude
See the Amplitude utilities section for detailed documentation and examples.
This plugin helps with SEO and SSR by ensuring search engines index only one version of a URL, avoiding duplicate content. It redirects URLs with a trailing slash to the version without it, making it easier for search engines to crawl your site consistently.
This plugin provides a mechanism for handling uncaught exceptions within your Fastify application, ensuring that such exceptions are logged and reported. It's especially useful for capturing unforeseen exceptions and provides a controlled shutdown of the Fastify server, thereby ensuring no potential data corruption.
#### Setup & Configuration
To integrate this plugin into your Fastify instance, follow these steps:
1. First, import the necessary types and the plugin:
`typescript`
import { FastifyInstance } from 'fastify'
import { unhandledExceptionPlugin, ErrorObjectResolver } from '@lokalise/fastify-extras'
2. Configure the plugin:
Define your own ErrorObjectResolver to dictate how the uncaught exceptions will be structured for logging. Here's an example:
`typescript`
const myErrorResolver: ErrorObjectResolver = (err, correlationID) => {
return {
error: err,
id: correlationID,
}
}
You'll also need to provide an ErrorReporter instance. This instance should have a report method to handle the error reporting logic. For example:
`typescript
import { ErrorReporter } from '@lokalise/node-core'
const myErrorReporter = new ErrorReporter(/ initialization params /)
`
3. Register the plugin with your Fastify instance:
`typescript
const fastify = Fastify()
fastify.register(unhandledExceptionPlugin, {
errorObjectResolver: myErrorResolver,
errorReporter: myErrorReporter,
})
`
#### Options
The plugin accepts the following options:
- errorObjectResolver (required): This function determines the structure of the error object which will be logged in case of an uncaught exception.
- errorReporter (required): An instance of the ErrorReporter which will handle reporting of the uncaught exceptions.
#### Working Principle
When an uncaught exception occurs, the plugin:
- Logs the exception using the provided errorObjectResolver.
- Reports the exception using the ErrorReporter.
- Shuts down the Fastify server gracefully.
- Exits the process with exit code 1.
#### Dependencies
- @lokalise/node-core: For error reporting.
- fastify: The framework this plugin is designed for.
> 🚨 It's critical to note that this plugin listens to the process's 'uncaughtException' event. Multiple listeners on this event can introduce unpredictable behavior in your application. Ensure that this is the sole listener for this event or handle interactions between multiple listeners carefully.
#### FakeAmplitude
FakeAmplitude is a utility class that extends Amplitude but doesn't send any events to Amplitude. This is useful for
testing environments or when you want to disable event tracking without changing your application code.
Example usage:
`typescript
import { FakeAmplitude } from '@lokalise/fastify-extras'
// In your test or development environment
const amplitude = new FakeAmplitude()
// track() will not send any events
amplitude.track({
event_type: 'button_clicked',
user_id: 'user-123',
})
`
The track() method returns a promise that resolves to null immediately, maintaining the same interface as the realAmplitude class without actually sending data.
#### AmplitudeAdapter
AmplitudeAdapter is a type-safe wrapper around Amplitude that uses Zod schemas to validate events before sending them.
This ensures that all events sent to Amplitude conform to predefined schemas, catching errors at compile-time and runtime.
Key features:
- Type-safe event tracking with TypeScript
- Automatic validation using Zod schemas
- Prevents sending malformed events to Amplitude
Example usage:
`typescript
import { z } from 'zod'
import { AmplitudeAdapter, AMPLITUDE_BASE_MESSAGE_SCHEMA, Amplitude } from '@lokalise/fastify-extras'
import type { AmplitudeMessage } from '@lokalise/fastify-extras'
// Define your event schemas
const eventSchemas = {
buttonClicked: {
schema: AMPLITUDE_BASE_MESSAGE_SCHEMA.extend({
event_type: z.literal('button_clicked'),
event_properties: z.object({
button_id: z.string(),
page: z.string(),
}),
}),
},
userSignedUp: {
schema: AMPLITUDE_BASE_MESSAGE_SCHEMA.extend({
event_type: z.literal('user_signed_up'),
event_properties: z.object({
plan: z.enum(['free', 'premium']),
}),
}),
},
} as const satisfies Record
const eventSchemaValues = Object.values(eventSchemas)
type SupportedEvents = typeof eventSchemaValues
// Create the adapter
const amplitude = new Amplitude(true)
const amplitudeAdapter = new AmplitudeAdapter
// Track events with type safety
amplitudeAdapter.track(eventSchemas.buttonClicked, {
user_id: 'user-123',
event_properties: {
button_id: 'submit-btn',
page: '/checkout',
},
})
// With groups
amplitudeAdapter.track(eventSchemas.userSignedUp, {
user_id: 'user-456',
groups: { company: 'acme-corp' },
event_properties: {
plan: 'premium',
},
})
`
Schema validation:
The AMPLITUDE_BASE_MESSAGE_SCHEMA provides the base schema that all events must extend. It requires:
- event_type: A literal string identifying the eventuser_id
- : A non-empty string or the literal 'SYSTEM'groups
- (optional): A record of group names to values
When defining custom events, extend this base schema with your specific event_type and event_properties:
`typescript`
const myEventSchema = AMPLITUDE_BASE_MESSAGE_SCHEMA.extend({
event_type: z.literal('my_custom_event'),
event_properties: z.object({
// Your custom properties with validation
count: z.number().int().positive(),
status: z.enum(['active', 'inactive']),
}),
})
If validation fails, a ZodError will be thrown, preventing invalid data from being sent to Amplitude.
#### authPreHandlers
- createStaticTokenAuthPreHandler - creates pre handler tha expects a static token in the Authorization` header. If value is different from the expected token, it will return a 401 response.