Understanding configuration types
In Fastify, we must consider splitting the configuration into three types to better organize our application:
- Server options: Provide the settings for the Fastify framework to start and support your application. We have presented them before when describing how to instantiate the server instance in the The root application instance section.
- Plugin configuration: Provides all the parameters to configure your plugins or the community plugins.
- Application configuration: Defines your endpoint settings.
This can be implemented with a configuration loader function:
const environment = process.env.NODE_ENV // [1] async function start () { const config = await staticConfigLoader(environment) // 2 const app = fastify(config.serverOptions.factory) app.register(plugin, config.pluginOptions.fooBar) app.register(plugin, { // [3] bar: function () { return config.pluginOptions ? 42 : -42 } }) await app.listen(config.serverOptions.listen) async function staticConfigLoader (env) { return { // [4] env, serverOptions: getServerConfig(), pluginOptions: {}, applicationOptions: {} } } } start()
This example shows the key points of a configuration loader:
- It must accept the environment as input. This will be fundamental during the test writing.
- It should be an async function: you will load settings from a different source that needs I/O.
- It must manage primitive types exclusively.
- It can be split into three main objects for clarity.
A plugin’s configuration often needs an input parameter that is not a primitive type-like function. This would be part of the code flow since a function acts based on input strings such as passwords, URLs, and so on.
This quick introduction shows you the logic we need to take into consideration when we build more complex code. This separation helps us to think about how to better split our configuration files. We will read a complete example in Chapter 6.
Now, we can configure and start our Fastify server; it is time to turn it off.