Search code examples
javascriptnode.jssendgriddotenv

Im working with a document config.env and it is not making work after of be called on index doc


For some reason the next code into config.env is not working, I'm using nodes libraries and I have dotenv library but the code is having an error with the tokens

CLIENT_URL = https://localhost:3000
JWT_ACCOUNT_ACTIVATION = 6f19abs00317c8e6f63f7661181313eb551f7a7b4c34c6ssssssssssssssssssssssssss0641f57e94ccabdd8d5be2fe07dfda21651473e0a39
JWT_SECRET = 764366csssssssssssssssssssssssssssssssssssssss9871e390c6d1214db7af574c0afc82d292aa96217aa647a88d3cc8accd4
JWT_RESET_PASSWORD = 1sssssssssssssssssssssssssssssss074dd9871e390c6d121asdqwdqwdqwdqwdqwdqwdf47a88d3cc8accd4
EMAIL_FROM = [email protected]
MAIL_KEY = SG.wwewewrrrrr9PXodfPNF3aALV1C10hI

The terminal is bringing me it

C:\xampp\htdocs\seth\api\src\config\config.env:1 CLIENT_URL = https://localhost:3000 ^

SyntaxError: Unexpected token ':'
    at wrapSafe (internal/modules/cjs/loader.js:1054:16)
    at Module._compile (internal/modules/cjs/loader.js:1102:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10)
    at Module.load (internal/modules/cjs/loader.js:986:32)
    at Function.Module._load (internal/modules/cjs/loader.js:879:14)
    at Module.require (internal/modules/cjs/loader.js:1026:19)
    at require (internal/modules/cjs/helpers.js:72:18)
    at Object.<anonymous> (C:\xampp\htdocs\seth\api\src\index.js:10:11)
    at Module._compile (internal/modules/cjs/loader.js:1138:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10)
[nodemon] app crashed - waiting for file changes before starting...

But I don't know why, I'm calling this document for a Rest API, and the method for being called is it:

const config = ("./config/config.env");

// Config dotev
require('dotenv').config({
    path: require(config)
})

All looks fine so I don't exactly know where's the problem


Solution

  • Node can't require plain files. Any files that use require to load need to be parsed by Node, so can be Javascript or JSON.

    To use your existing code, the config file should be JSON (or js)

    {
    "CLIENT_URL": "https://localhost:3000",
    "JWT_ACCOUNT_ACTIVATION": "xxx"
    }
    

    Alternatively dotenv can load that config

    require('dotenv').config({ path: './config/config.env' })
    

    I'm not sure about the spaces, it might need values like:

    CLIENT_URL=https://localhost:3000
    JWT_ACCOUNT_ACTIVATION=xxx