Dan Rubio Dan Rubio - 9 days ago 4
Node.js Question

const url = {process.env.REACT_APP_DATABASE} SyntaxError: Unexpected token

I have a file in

mongo.js
where I have set an ENV variable like so:

const mongo = require('mongodb').MongoClient;
const assert = require('assert');
const ObjectId = require('mongodb').ObjectID;
const express = require('express');
const url = {process.env.REACT_APP_DATABASE}
const bodyParser = require('body-parser');
const app = express();


When I try to run
node mongo.js
I receive this error:

/Users/drubio/Desktop/react_personal_website/src/modules/mongo.js:5
const url = {process.env.REACT_APP_DATABASE}
^
SyntaxError: Unexpected token .
at Object.exports.runInThisContext (vm.js:78:16)
at Module._compile (module.js:545:28)
at Object.Module._extensions..js (module.js:582:10)
at Module.load (module.js:490:32)
at tryModuleLoad (module.js:449:12)
at Function.Module._load (module.js:441:3)
at Module.runMain (module.js:607:10)
at run (bootstrap_node.js:420:7)
at startup (bootstrap_node.js:139:9)
at bootstrap_node.js:535:3


According to create-react-app, I should be able to set environment variables this way. I have even created a
.env
file and the contents of the file has the url that I want to connect to:

REACT_APP_DATABASE = 'mongodb://localhost:27017/danielrubio'


Why am I getting this syntax error. I've restarted both servers so it should work.

lux lux
Answer

This is not valid JavaScript syntax:

const url = { process.env.REACT_APP_DATABASE }

If you are creating an object literal, it needs to be in [key]:[value] format:

const url = { url: process.env.REACT_APP_DATABASE}

However, if you are trying to just get the variable:

const url = process.env.REACT_APP_DATABASE;