Dan Rubio Dan Rubio - 1 year ago 165
Node.js Question

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

I have a file in

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:

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
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 Source

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;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download