sslhttpsvite

Vite https on localhost


I'm trying to get https working on my localhost environment for Vite. Chrome shows an invalid certificate error.

I've set up my vite.config.js file like this:

import { defineConfig  } from 'vite'
import vue from '@vitejs/plugin-vue'
import fs from 'fs';

export default defineConfig({
  resolve: { alias: { '@': '/src' } },
  plugins: [vue()],
  https: {
    key: fs.readFileSync('RootCA-key.pem'),
    cert: fs.readFileSync('RootCA.pem')
  }
})

and when I run npm run dev -- --https it works as expected, I don't get any issues from Vite. However, Chrome shows an invalid certificate.

I used openssl to create the cert files, which gave me .crt, .pem, and .key files. None of them are binary, so I renamed the .key file as RootCA-key.pem. I've tried using the RootCA.pem file as the cert, as well as renaming the RootCA.crt file to RootCA-cert.pem and using that as the cert.

As a temporary work-around, I've enabled insecure localhost in Chrome (chrome://flags/#allow-insecure-localhost), which at least gets rid of the warning.


Solution

  • The Vite documentation suggest using their official package instead: @vitejs/plugin-basic-ssl

    Documentation: https://vitejs.dev/config/server-options.html#server-https

    You need to install it with

    npm install -D @vitejs/plugin-basic-ssl
    

    And then use it like this in your vite.config.ts:

    import basicSsl from '@vitejs/plugin-basic-ssl'
    
    export default {
      plugins: [
        basicSsl()
      ]
    }
    

    ⚠️ This is for your dev environment, don't use this on production. You need your own certificate in production (using nginx and let's encrypt for example).