node.js - Fastify: Is it possible to access envs registered in one file via fastify-env in another file? - TagMerge
3Fastify: Is it possible to access envs registered in one file via fastify-env in another file?Fastify: Is it possible to access envs registered in one file via fastify-env in another file?

Fastify: Is it possible to access envs registered in one file via fastify-env in another file?

Asked 11 months ago
1
3 answers

Fastify does NOT set any global values. So, snippets like this will never work:

//WRONG EXAMPLE
const fastify = require('fastify');
console.log('from db.js', fastify.config); // undefined

A simpler way to accomplish your need is:

const initialize = async () => {
  const fastify = require('fastify')()
  await fastify.register(require('./setup/envs'))
  console.log('config is: ', fastify.config.DATABASE_NAME) // works. 
  fastify.register(require('./setup/db'));
  return fastify
}

initialize()
  .then((app)=>{
    console.log('fastify config is: ', app.config)
  })

And then:


async function dbConnector (fastify, options) {
  // I'm using the fastify input argument
  const dbUser = encodeURIComponent(fastify.config.DATABASE_USERNAME)
  const dbPassword = encodeURIComponent(fastify.config.DATABASE_PASSWORD);
  const dbHost = encodeURIComponent(fastify.config.DATABASE_HOST);
  const dbName = encodeURIComponent(fastify.config.DATABASE_NAME);

  fastify.register(fastifyPostgres, {
    connectionString: `postgres://${dbUser}@${dbHost}/${dbName}`
  })
}

module.exports = fastifyPlugin(dbConnector);

Source: link

0

It turns out, I can access fasty.config within the dbConnector function and not outside of it after registering the env plugin by using .after() as shown here: https://github.com/fastify/fastify/blob/main/docs/Reference/Plugins.md#handle-the-scope.

Anyways, these are the changes I made.

in app.js:

const fastify = require('fastify')({logger: true})

fastify.register(require('./setup/envs'))
       .after(err => {
          if (err) console.log(err);
          fastify.register(require('./setup/db'))
       })

fastify.get('/hello', (req, reply) => {
  return { hello: 'world' }
})


const start = async () => {
  try {
    await fastify.ready()
    fastify.listen(3000)
  } catch (e) {
    fastify.log.error(e)
    process.exit(1)
  }
}

start();

and in db.js:

const fastifyPlugin = require('fastify-plugin');
const fastifyPostgres = require('fastify-postgres');


// can use process.env here 
const dbUser = encodeURIComponent(process.env.DATABASE_USERNAME)
const dbPassword = encodeURIComponent(process.env.DATABASE_PASSWORD);
const dbHost = encodeURIComponent(process.env.DATABASE_HOST);
const dbName = encodeURIComponent(process.env.DATABASE_NAME);

async function dbConnector (fastify, options) {
  // or use fasty.config here
  //   ...
  // const dbName = encodeURIComponent(fastify.config.DATABASE_NAME);

  fastify.register(fastifyPostgres, {
    connectionString: `postgres://${dbUser}:${dbPassword}@${dbHost}/${dbName}`
  })
}
// Wrapping a plugin function with fastify-plugin exposes the decorators
// and hooks, declared inside the plugin to the parent scope.
module.exports = fastifyPlugin(dbConnector);

Not sure why, for example, process.env.DATABASE_USERNAME gives me the value but fastify.config.DATABASE_USERNAME doesn't but oh wells.

Source: link

0

Bump @types/node from 16.11.14 to 17.0.0 (#128)
Bumps [@types/node](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/node) from 16.11.14 to 17.0.0.
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/node)

---
updated-dependencies:
- dependency-name: "@types/node"
  dependency-type: direct:development
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Install
npm install --save fastify-env
Usage
const fastify = require('fastify')()
const fastifyEnv = require('fastify-env')

const schema = {
  type: 'object',
  required: [ 'PORT' ],
  properties: {
    PORT: {
      type: 'string',
      default: 3000
    }
  }
}

const options = {
  confKey: 'config', // optional, default: 'config'
  schema: schema,
  data: data // optional, default: process.env
}

fastify
  .register(fastifyEnv, options)
  .ready((err) => {
    if (err) console.error(err)

    console.log(fastify.config) // or fastify[options.confKey]
    // output: { PORT: 3000 }
  })
This module is a wrapper around env-schema. To read an .env file you must set dotenv in the options:
const options = {
  dotenv: true // will read .env in root folder
}

// or, pass config options avalible on dotenv module
const options = {
  dotenv: {
    path: `${__dirname}/.env`,
    debug: true
  }
}
In order to have typing for the fastify instance, you should follow the example below:
declare module 'fastify' {
  interface FastifyInstance {
    config: { // this should be same as the confKey in options
      // specify your typing here
    };
  }
}

Source: link

Recent Questions on node.js

    Programming Languages