Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

TypeError: Cannot read property 'PORT' of undefined at Object... #2

Open
davidshq opened this issue Dec 15, 2020 · 4 comments
Open

Comments

@davidshq
Copy link

When implementing the fastify-env plugin as outlined in your SitePoint article I'm getting an error:

E:\js-fastify\index.js:50
app.listen(app.config.PORT, (err, address) => {
                      ^

TypeError: Cannot read property 'PORT' of undefined
    at Object.<anonymous> (E:\js-fastify\index.js:50:23)
    at Module._compile (internal/modules/cjs/loader.js:1158:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1178:10)
    at Module.load (internal/modules/cjs/loader.js:1002:32)
    at Function.Module._load (internal/modules/cjs/loader.js:901:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12)
    at internal/main/run_main_module.js:18:47

My index.js file looks like this:

// Require the framework and instantiate it
const app = require('fastify')({
    logger: true
})

// Use Fastify Env plugin: https://github.com/fastify/fastify-env
const fastifyEnv = require('fastify-env') // load plugin

const options = {
    confKey: 'config', // optional, default: 'config'
    schema: {
        type: 'object',
        required: ['PORT'],
        properties: {
            PORT: {
                type: 'string',
                default: 1000
            }
        }
    }
}

app
    .register(fastifyEnv, options)
    .ready((err) => {
        if (err) console.log(err)

        console.log(app.config)
        // output: { PORT: 1000 }
    })


// hooks
app.addHook('onRoute', (routeOptions) => {
    console.log(`Registered route: ${routeOptions.url}`)
})

// Declare a route
app.get('/', function(req, reply) {
    reply.send({ hello: 'world' })
})

// Register routes to handle blog posts
const blogRoutes = require('./routes/blogs')
blogRoutes.forEach((route, index) => {
    app.route(route)
})

// Run the server
app.listen(app.config.PORT, (err, address) => {
    if (err) {
        app.log.error(err)
        process.exit(1)
    }
    app.log.info(`server listening on ${address}`)
})

Any suggestions? I noted that in the index.js here you have the port hard-coded rather than using the fastify-env plugin.

Thanks!

@michielmulders
Copy link
Owner

Hi Dave, thanks for both comments!

I remember the issue vaguely, but this is what I know: I think the plugin needs to be loaded using an await to be able to access the env vars directly from the app object.

As all of the above calls happen async, the app.config.PORT is still undefined by the time the code reaches app.listen. It's not a great plugin in that sense - using dotenv might be cleaner although I like the added validation/default values.

@EnergeticPixels
Copy link

@davidshq I have discovered the same issue that you did. Quite by mistake. I played with the fastify-env config targeting in the app.listen object for 2 hours. I finally gave up and went back to what I knew that would work -- old fashion dotenv. Outside of that this easy sample of fastify separate routes and controllers worked perfectly.

@michielmulders
Copy link
Owner

Well, I agree that using dotenv here simplifies things and is more of an industry best practice than using fastivy-env. Sorry for adding that confusion to the article!

@EnergeticPixels
Copy link

EnergeticPixels commented Jan 19, 2021 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants