[Vuejs]-Load custom configuration runtime

0๐Ÿ‘

โœ…

If someone else has this kind of problem here is the solution I came up with in the end:

// plugins/config.js
class Settings
{
  constructor (app, req) {
    if (process.server) {
      // Server side we load the file simply by using fs
      const fs = require('fs');
      this.json = fs.readFileSync('config.json');
    } else {
      // Client side we make a request to the server
      fetch('/config')
        .then((response) => {
          if (response.ok) {
            return response.json();
          }
        })
        .then((json) => {
          this.json = json;
        });
       }
     }
}

export default function ({ req, app }, inject) {
  inject('config', new Settings(app, req));
};

For this to work we need to use a server middleware:

// api/config.js
const fs = require('fs');
const express = require('express');
const app = express();

// Here we pick up requests to /config and reads and return the
// contents of the configuration file
app.get('/', (req, res) => {
  fs.readFile('config.json', (err, contents) => {
    if (err) {
      throw err;
    }
    res.set('Content-Type', 'application/json');
    res.end(contents);
  });
});

module.exports = {
  path: '/config',
  handler: app
};

Leave a comment