Instrumentation is a new feature introduced in Next.js 14 that allows you to run custom logic when your application starts. The instrumentation.ts/js

Instrumenting Next.js with runtime secret injection

submited by
Style Pass
2025-07-27 17:00:03

Instrumentation is a new feature introduced in Next.js 14 that allows you to run custom logic when your application starts. The instrumentation.ts/js file lives at the root of your Next.js project and exposes a register() API, which will be called once when a new Next.js server instance is initiated.

Instrumentation is most often used to initiate logging or telemetry services. This example from Vercel's docs shows a basic example of how this works:

As we've seen, the register() API is meant primarily for running code at startup and initializing services or tools that can be used later during application runtime. This lends itself nicely as a way to inject secrets into our app. We've discussed the benefits of runtime secret injection, specifically in the context of Next.js in a previous post, so have a look at that if you want to know more. The TL;DR is that it keeps secrets out of code, version control, and build artifacts. Runtime secret injection also makes your application more portable and easier to distribute, either within your team or for public consumption.

Next.js evaluates (server-side) secrets and environment variables at runtime, if provided as a .env file. While this works, it comes with a number of drawbacks, security concerns, and clumsy DX. We've covered this topic in-depth in another post, but in short, .env files are problematic because they often end up in version control or left lying on local disks unencrypted, increasing the risk of a secret leak. They're nearly impossible to manage securely at scale, are difficult to distribute across a team, and offer no access control or security. Secret management tools offer encryption, access controls, easy collaboration, auditing, and rotation, making them a much safer, scalable, and developer friendly solution.

Leave a Comment
Related Posts