Using HTTPS on localhost in Nuxt

So you’re here because you need your localhost to run on https for your Nuxt.js project.  That used to be tougher, but in the latest version of Nuxt.js it’s very straight forward.  Let’s go over the steps from the top:

Let’s start with opening your project in Visual Studio Code, and opening a terminal in the root of the project (through Visual Studio Code).

Then following the following:

  • Add this to your terminal:
    openssl genrsa 2048 > server.key
    chmod 400 server.key
    openssl req -new -x509 -nodes -sha256 -days 365 -key server.key -out server.crt
    • You’ll then fill out the needed info
    • Should generate a server.crt & server.key 
  • Then in your nuxt.config.js, at the top, add the following `const`
    const path = require('path');
    const fs = require('fs');
  • Then in your configuration settings:
    server: {
      https: {
        key: fs.readFileSync(path.resolve(__dirname, 'server.key')),
        cert: fs.readFileSync(path.resolve(__dirname, 'server.crt'))
      }
    }
  • Then go to the index.js in your server folder: server > index.js
  • add the following const at the top
    const https = require('https')
  • the comment out and replace the following:
    // app.listen(port, host);
    https.createServer(nuxt.options.server.https, app).listen(port, host);
  • When you run your project locally you’ll be able to run it under HTTPS