How to store access token as an environment variable (no hardcoding)?

I was wondering, I am new to Hubspot development, and I would like to know, how would I store my access token as an environment variable (no hardcoding). We eventually want to put this code on a live server, and for security reasons I don’t want to have a hardcoded access token in my code. All the information on the web seems to only talk about the old method of API keys.

This is my current code:

const express = require(‘express’);

const axios = require(‘axios’);

const app = express();

const hubspot = require(‘@hubspot/api-client’);

const private_app_token = ‘my_token’

const hubspotClient = new hubspot.Client({“accessToken”:private_app_token});

const companyIdConst = window.location.href.lastIndexOf(‘/’) + 1;

app.get(‘/companies’, async (req, res) => {

const companyId = companyIdConst;

const properties = [“zip”];

const propertiesWithHistory = undefined;

const associations = undefined;

const archived = false;

const idProperty = undefined;

try {

const apiResponse = await hubspotClient.crm.companies.basicApi.getById(companyId, properties, propertiesWithHistory, associations, archived, idProperty);

const data = apiResponse.results;

//res.json(data);

console.log(JSON.stringify(apiResponse.properties.zip, null, 2));

} catch (e) {

e.message === ‘HTTP request failed’

? console.error(JSON.stringify(e.response, null, 2))

: console.error(e)

}

});

app.listen(3000, () => console.log(‘Listening on http://localhost:3000’));

Hey, @ChrisSosa1337 :waving_hand: Thanks for the great question. I have some best practices type suggestions. If you’ve tried these already, please let the community know, and we’ll see if the community has other ways to accomplish this goal.

  • If you are using a Unix-based system (like macOS or Linux), you can set it in your .bashrc or .zshrc
    export HUBSPOT_ACCESS_TOKEN=your_actual_token_here
  • dotenv is a pretty common package when using Node.js
    npm install dotenv​
  • Create an .env file in your root of your project
    HUBSPOT_ACCESS_TOKEN=your_actual_token_here​
  • You could replace your hardcoded token like this
    const private_app_token = process.env.HUBSPOT_ACCESS_TOKEN;​
  • Important: Make sure to add .env to your .gitignore file to prevent accidentally pushing your access token to a public repository

One additional question, is this part of your code returning the company ID as expected?

const companyIdConst = window.location.href.lastIndexOf('/') + 1;

Talk soon! — Jaycee