Access privateRuntimeConfig in express server

Viewed 169

I've installed the express-nuxt template and I was wondering how could I get access to the privateRuntimeConfig inside nuxt.config.js from express (API folder). One approach I thought about was to put the vars inside a .env file and then installing the dotenv package for the express server, but I think that using just Nuxt could be better.

1 Answers

We have done precisely this by importing the Nuxt config into the file that configures the Express app, and using defu to combine public and private runtime configs, as Nuxt itself does:


    // nuxt.config.js

    export default {
      publicRuntimeConfig: {},
      privateRuntimeConfig: { redis: { url: process.env['REDIS_URL'] } }
    };


    // api/index.js

    import express from 'express';
    import defu  from 'defu';
    import { createClient as createRedisClient } from 'redis';
    
    const app = express();
    
    import nuxtConfig from '../nuxt.config.js';
    let runtimeConfig;
    
    app.use((req, res, next) => {
      if (!runtimeConfig) {
        // Load Nuxt config once, at runtime
        runtimeConfig = defu(nuxtConfig.privateRuntimeConfig, nuxtConfig.publicRuntimeConfig);
      }
      next();
    });
    
    // Subsequent middlewares will then be able to read from `runtimeConfig`
    app.use((req, res, next) => {
      const redisClient = createRedisClient({ url: runtimeConfig.redis.url });
      next();
    });
    
    export default app;

Related