Put all credential to file .json

Viewed 1421

i am new at Javascript, and i still confuse about javascript and using json file. I working at one of my office project about sending a message, i have been complete all the code at back-end and front-end, but when the code was review with my project leader, he say to put all the credential to file json. To send a message / mail, i using nodemailer from node.js

Here is the credential i have to put in json file

const transporter = mail.createTransport({ //unresolved
  service: 'Gmail',
  host: 'smtp.gmail.com',
  auth: {
    user: 'no.replyxx@xx.org',
    pass: 'xxxxxx'
  }
});

I have put it into the json file, but when i call it at my javascript file, i don't know how to call it, i try to import a json file, but i just get bug for it can someone help me, precisely my question is how i write a credential to json file and how i use it at my javascript? Thanks

4 Answers

You should look into using dotenv

You can use it like so

// this will find the .env file at the root of your project
// and parse the entries into key/value pairs on the `process.env` object
require('dotenv').config()

const transporter = mail.createTransport({ //unresolved
  service: 'Gmail',
  host: 'smtp.gmail.com',
  auth: {
    user: process.env.MAIL_USER,
    pass: process.env.MAIL_PASS
  }
});

Create a .env file at the root of your project

// .env

MAIL_USER=no.replyxx@xx.org
MAIL_PASS=secret-password

Also, you should ensure that this does not get committed to your version control system.
If you're using git, create a .gitignore and make sure you have an entry for .env

// .gitignore

.env

First thing, in JSON, there is no const. const comes from JS. If you want to save your credentials to a JSON file, it will contain something like this:

{
  "service": "Gmail",
  "host": "smtp.gmail.com",
  "auth": {
    "user": "no.replyxx@xx.org",
    "pass": "xxxxx"
  }
}

also, it needs double quotes and not single quotes.

After this all you need to do is require it

const credentials = require('./jsonCredentials.json');

First, you can import the content of a file using the fs library method called fs.readFileSync(filePath).

Then, you parse the content into a JSON object using the JSON.parse(content) method.

From there, you can have the JSON content as an object, and you can now use it in your createTransport method call.

I just want to add that I recommend using .env files which are more secure.

But to answer your question, Since I'm assuming you're using ReactJS, you can do something like this:

config.js

export default const config = {
  service: 'Gmail',
  host: 'smtp.gmail.com',
  auth: {
    user: 'no.replyxx@xx.org',
    pass: 'xxxxxx'
  }
}

Then simply import to use it

import config from './config.js'

function myFunction()
{
  const transporter = mail.createTransport(config);
}
Related