I have a node.js express app with a app.js file, a deviceController.js file, and a cart.pug file. I need to access two constants for the Stripe API in deviceController.js and cart.pug and want to set their values in app.js.

I tried app.set/app.get but get "app is undefined" in deviceController.js and I don't want to make a global variable with var.

What is the best practice way to do this?


const express = require('express');
const routes = require('./routes/index');

const app = express();

// **want these constants available in deviceController.js and cart.pug** 
const keyPublishable = process.env.PUBLISHABLE_KEY;
const keySecret = process.env.SECRET_KEY;

app.set('view engine', 'pug');

module.exports = app;


const stripe = require('stripe')(keySecret);


extends layout

block content
    form(action="/payment" method="POST")
        src="https://checkout.stripe.com/checkout.js" class="stripe-button"

1 Answers

Gonzalo.- On

you should create a module for your process constants - that way you can require them anywhere you want, without directly accessing process.

// constants.js

module.exports = {
  stripe: { // you could also use stripeKeys or whatever
     keyPublishable: process.env.PUBLISHABLE_KEY;
     keySecret: process.env.SECRET_KEY;

then in each file

// deviceController.js
const { stripe } = require('./constants.js');
// use stripe.keyPublishable or stripe.keySecret

and in the templates

// when compiling the pug file, you also require the constants file and pass it
// template.pug has #{keyPublishable}
const { stripe } = require('./constants.js');
// .. rest of code
pug.renderFile('template.pug', {
  keyPublishable : stripe.keyPublishable 

Check docs on how to pass objects to be interpolated by pug template