DEV Community

Romildo Junior
Romildo Junior

Posted on

5 3

Making a dead simple configuration service with Typescript

If you're working with NodeJS applications, you probably has process.env.VARIABLE statements all around your code base. The most simple method to configure an application is installing dotenv and creating that lovely .env file on the root folder of your project.

This approach, however, has some pitfalls and is error prone. What if you don't set that process.env port? You'll probably have a default value (maybe 3000?), but you will need to run your application to discover such type of thing.

That same problem has been solved by typescript for almost anything. When you have the help of static typing, you can discover some errors a lot faster. That said, how can you use Typescript to have a type-safe way to access configurations?

Show me the code!

Take a look at that short snippet:

export class EnvironmentService<Environment> {

  public constructor(
   private readonly variables: Environment
  ) {
    // some logic to assign process.env to this.variables
    // you can use, for instance, 
    this.variables = Joi.attempt<Environment>(process.env))
  }

  public get<T>(name: keyof Environment) {
    return <T><unknown>this.variables[name];
  }
}
Enter fullscreen mode Exit fullscreen mode

In a nutshell,

  • First, you need to define an interface for you environment;
  • Then, you do pass it as a type parameter to the EnvironmentService class when instantiating a new object;
  • Finally, use something like class-validator, Joi or you library of choice to assert if the process.env object has all required variables and assign its value to the variables attribute;

After those simple steps, you can use the method get to fetch all possible environment variables with the help of typescript to guide your choice - and if you need, you can cast the value to some desired type:

Test

Conclusion

That's all folks! If you liked that simple content, don't forget to comment and share with someone you might help. Also, that's my first attempt to write something in english: if you see something wrong, just message me on Twitter (@dotmendes).

References

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more