[node.js] create a trusted self-signed SSL cert for localhost (for use with Express/Node)

Trying to follow various instructions on creating a self-signed cert for use with localhost, Most of the instructions seem to be for IIS, but I'm trying to use Nodejs/Express. None of them work properly because while the cert gets installed, it is not trusted. here's what I've tried that fails:

Can someone offer a workflow that can do this? I can get a cert installed, but I can't get the cert to be trusted in either chrome (v32) or IE (v10).

EDIT: it was suggested in comments that the problem is no trusted cert-root. I installed the cert via IE but it's still not being trusted.

This question is related to node.js express openssl localhost ssl-certificate

The answer is


Here's what's working for me

on windows

1) Add this to your %WINDIR%\System32\drivers\etc\hosts file: 127.0.0.1 localdev.YOURSITE.net (cause browser have issues with 'localhost' (for cross origin scripting)

Windows Vista and Windows 7 Vista and Windows 7 use User Account Control (UAC) so Notepad must be run as Administrator.

  1. Click Start -> All Programs -> Accessories

  2. Right click Notepad and select Run as administrator

  3. Click Continue on the "Windows needs your permission" UAC window.

  4. When Notepad opens Click File -> Open

  5. In the filename field type C:\Windows\System32\Drivers\etc\hosts

  6. Click Open

  7. Add this to your %WINDIR%\System32\drivers\etc\hosts file: 127.0.0.1 localdev.YOURSITE.net

  8. Save

  9. Close and restart browsers

On Mac or Linux:

  1. Open /etc/hosts with su permission
  2. Add 127.0.0.1 localdev.YOURSITE.net
  3. Save it

When developing you use localdev.YOURSITE.net instead of localhost so if you are using run/debug configurations in your ide be sure to update it.

Use ".YOURSITE.net" as cookiedomain (with a dot in the beginning) when creating the cookiem then it should work with all subdomains.

2) create the certificate using that localdev.url

TIP: If you have issues generating certificates on windows, use a VirtualBox or Vmware machine instead.

3) import the certificate as outlined on http://www.charlesproxy.com/documentation/using-charles/ssl-certificates/


There are more aspects to this.

You can achieve TLS (some keep saying SSL) with a certificate, self-signed or not.

To have a green bar for a self-signed certificate, you also need to become the Certificate Authority (CA). This aspect is missing in most resources I found on my journey to achieve the green bar in my local development setup. Becoming a CA is as easy as creating a certificate.

This resource covers the creation of both the CA certificate and a Server certificate and resulted my setup in showing a green bar on localhost Chrome, Firefox and Edge: https://ram.k0a1a.net/self-signed_https_cert_after_chrome_58

Please note: in Chrome you need to add the CA Certificate to your trusted authorities.


If you're on OSX/Chrome you can add the self-signed SSL certificate to your system keychain as explained here: http://www.robpeck.com/2010/10/google-chrome-mac-os-x-and-self-signed-ssl-certificates

It's a manual process, but I got it working finally. Just make sure the Common Name (CN) is set to "localhost" (without the port) and after the certificate is added make sure all the Trust options on the certificate are set to "Always Trust". Also make sure you add it to the "System" keychain and not the "login" keychain.


You can try openSSL to generate certificates. Take a look at this.

You are going to need a .key and .crt file to add HTTPS to node JS express server. Once you generate this, use this code to add HTTPS to server.

var https = require('https');
var fs = require('fs');
var express = require('express');

var options = {
    key: fs.readFileSync('/etc/apache2/ssl/server.key'),
    cert: fs.readFileSync('/etc/apache2/ssl/server.crt'),
    requestCert: false,
    rejectUnauthorized: false
};


var app = express();

var server = https.createServer(options, app).listen(3000, function(){
    console.log("server started at port 3000");
});

This is working fine in my local machine as well as the server where I have deployed this. The one I have in server was bought from goDaddy but localhost had a self signed certificate.

However, every browser threw an error saying connection is not trusted, do you want to continue. After I click continue, it worked fine.

If anyone has ever bypassed this error with self signed certificate, please enlighten.


If you need to go a step further than @alon's detailed steps and also create a self signed ca:

https.createServer({
  key: fs.readFileSync(NODE_SSL_KEY),
  cert: fs.readFileSync(NODE_SSL_CERT),
  ca: fs.readFileSync(NODE_SSL_CA),
}, app).listen(PORT, () => {});

package.json

"setup:https": "openssl genrsa -out src/server/ssl/localhost.key 2048
&& openssl req -new -x509 -key src/server/ssl/localhost.key -out src/server/ssl/localhost.crt -config src/server/ssl/localhost.cnf
&& openssl req -new -out src/server/ssl/localhost.csr -config src/server/ssl/localhost.cnf
&& openssl x509 -req -in src/server/ssl/localhost.csr -CA src/server/ssl/localhost.crt -CAkey src/server/ssl/localhost.key -CAcreateserial -out src/server/ssl/ca.crt",

Using the localhost.cnf as described:

[req]
distinguished_name = req_distinguished_name
x509_extensions = v3_req
prompt = no
[req_distinguished_name]
C = UK
ST = State
L = Location
O = Organization Name
OU = Organizational Unit 
CN = www.localhost.com
[v3_req]
keyUsage = critical, digitalSignature, keyAgreement
extendedKeyUsage = serverAuth
subjectAltName = @alt_names
[alt_names]
DNS.1 = www.localhost.com
DNS.2 = localhost.com
DNS.3 = localhost

If you're using node, why not generate them with node? This module seems to be pretty full featured:

Note that I wouldn't generate on the fly. Generate with some kind of build script so you have a consistent certificate and key. Otherwise you'll have to authorize the newly generated self-signed certificate every time.


on windows I made the iis development certificate trusted by using MMC (start > run > mmc), then add the certificate snapin, choosing "local computer" and accepting the defaults. Once that certificate snapip is added expand the local computer certificate tree to look under Personal, select the localhost certificate, right click > all task > export. accept all defaults in the exporting wizard.

Once that file is saved, expand trusted certificates and begin to import the cert you just exported. https://localhost is now trusted in chrome having no security warnings.

I used this guide resolution #2 from the MSDN blog, the op also shared a link in his question about that also should using MMC but this worked for me. resolution #2


How to generate an SSL certificate for localhost: link

openssl genrsa -des3 -out server.key 1024

you need to enter a password here which you need to retype in the following steps

openssl req -new -key server.key -out server.csr

when asked "Common Name" type in: localhost

openssl x509 -req -days 1024 -in server.csr -signkey server.key -out server.crt

SMH, a lot of hours wasted on this due to lack of proper documentation and not everyone uses IIS... If anyone else is still stuck on this issue I hope this helps.

Solution: Trusted Self Signed SSL CERT for localhost on Windows 10

Note: If you only need the SSL cert follow the Certification Creation section

Stack: Azure Function App(Node.js), React.js - Windows 10

Certification Creation

Step 1 - Create Certificate: OpenPowershell and run the following:

New-SelfSignedCertificate -NotBefore (Get-Date) -NotAfter (Get-Date).AddYears(5) `
-Subject "CN=localhost" -KeyAlgorithm "RSA" -KeyLength 2048 `
-HashAlgorithm "SHA256" -CertStoreLocation "Cert:\CurrentUser\My" `
-FriendlyName "HTTPS Development Certificate" `
-TextExtension @("2.5.29.19={text}","2.5.29.17={text}DNS=localhost")

Step 2 - Copy Certificate: Open Certificate Manager by pressing the windows key and search for "manage user certificates". Navigate to Personal -> Certificates and copy the localhost cert to Trusted Root Certification Authorities -> Certificates

Personal -> Certificates

Trusted Root Certification Authorities -> Certificates

(Friendly Name will be HTTPS Development Certificate)

Step 3. Export Certificate right click cert -> All Tasks -> Export which will launch the Certificate Export Wizard: Certificate Export Wizard

  • Click next
  • Select Yes, export the private Key Export private key
  • Select the following format Personal Information Exchange - PKCS #12 and leave the first and last checkboxes selected. Export format
  • Select a password; enter something simple if you like ex. "1111" Enter password
  • Save file to a location you will remember ex. Desktop or Sites (you can name the file development.pfx) Save file

Step 4. Restart Chrome

Azure Function App (Server) - SSL Locally with .PFX

In this case we will run an Azure Function App with the SSL cert.

  • copy the exported development.pfx file to your azure functions project root
  • from cmd.exe run the following to start your functions app func start --useHttps --cert development.pfx --password 1111" (If you used a different password and filename don't forget to update the values in this script)
  • Update your package.json scripts to start your functions app:

React App (Client) - Run with local SSL

Install openssl locally, this will be used to convert the development.pfx to a cert.pem and server.key. Source - Convert pfx to pem file

  1. open your react app project root and create a cert folder. (project-root/cert)
  2. create a copy of the development.pfx file in the cert folder. (project-root /cert/development.pfx)
  3. open command prompt from the cert directory and run the following:
  4. convert development.pfx to cert.pem: openssl pkcs12 -in development.pfx -out cert.pem -nodes
  5. extract private key from development.pfx to key.pem: openssl pkcs12 -in development.pfx -nocerts -out key.pem
  6. remove password from the extracted private key: openssl rsa -in key.pem -out server.key
  7. update your .env.development.local file by adding the following lines:
SSL_CRT_FILE=cert.pem
SSL_KEY_FILE=server.key
  1. start your react app npm start

Go to: chrome://flags/

Enable: Allow invalid certificates for resources loaded from localhost.

You don't have the green security, but you are always allowed for https://localhost in chrome.


Some of the answers posted have pieces that were very useful to me to overcome this problem too. However, I was also interested in the minimum number of steps and, ideally, avoiding OpenSSL (on Windows 10).

So, one critical piece from the answers (credit: @TroyWorks) is that you need to edit your HOSTS file to create a fictitious server, and map that to 127.0.0.1. This assumes you are going to be doing local development.

In my case, I was using the SS certificate to secure a websocket in NodeJS, and that socket was being connected to programmatically (as opposed to via browser). So for me, it was critical that the certificate be accepted without warnings or errors, and the critical piece there was to get the cert created with a proper CN (and of course accept the cert into Trusted Authorities, as described elsewhere in the answers). Using IIS to create a self-signed cert won't create the proper CN, so I discovered the following simple command using Powershell:

New-SelfSignedCertificate -DnsName "gandalf.dummy.dev" -FriendlyName "gandalf" -CertStoreLocation "cert:\LocalMachine\My"

This has to be run in the PS Admin console, but it simply works, and puts the cert into the "Personal" section of the LocalMachine certificate store. You can verify it got created by executing:

ls cert:\LocalMachine\My 

To trust it, simply copy this and paste into "Trusted Root Certification Authorities" using Certificate Manager (making sure you are looking at the Local Machine certificates, not Current User!).

If you bind to this certificate in IIS, you should be able to hit https://gandalf.dummy.dev/ and get a secure connection without any warnings.

The final piece, using this in NodeJS, is described above and in other SO answers, so I'll only add that on Windows, it is easier to work with a pfx file that combines the cert and private key. You can export a pfx easily from the Certificate Manager, but it does affect how you use it in NodeJS. When instantiating a Server using the 'https' module, the options you would use (instead of 'key' and 'cert') would be 'pfx' and 'passphrase', as in:

var https = require('https');
var options = { 
    pfx: fs.readFileSync('mypfxfile'), 
    passphrase: 'foo' 
};
var server = https.createServer(options);

Mkcert from @FiloSottile makes this process infinitely simpler:

  1. Install mkcert, there are instructions for macOS/Windows/Linux
  2. mkcert -install to create a local CA
  3. mkcert localhost 127.0.0.1 ::1 to create a trusted cert for localhost in the current directory
  4. You're using node (which doesn't use the system root store), so you need to specify the CA explicitly in an environment variable, e.g: export NODE_EXTRA_CA_CERTS="$(mkcert -CAROOT)/rootCA.pem"
  5. Finally run your express server using the setup described in various other answers (e.g. below)
  6. boom. localhost's swimming in green.

Basic node setup:

const https = require('https');
const fs = require('fs');
const express = require('express');

const app = express();    
const server = https.createServer({
    key: fs.readFileSync('/XXX/localhost+2-key.pem'), // where's me key?
    cert: fs.readFileSync('/XXX/localhost+2.pem'), // where's me cert?
    requestCert: false,
    rejectUnauthorized: false,
}, app).listen(10443); // get creative

Shortest way. Tested on MacOS, but may work similarly on other OS.

Generate pem

> openssl req -x509 -newkey rsa:2048 -keyout keytmp.pem -out cert.pem -days 365

> openssl rsa -in keytmp.pem -out key.pem

Your express server

const express = require('express')
const app = express()
const https = require('https')
const fs = require('fs')
const port = 3000

app.get('/', (req, res) => {
  res.send('WORKING!')
})

const httpsOptions = {
  key: fs.readFileSync('./key.pem'),
  cert: fs.readFileSync('./cert.pem')
}
const server = https.createServer(httpsOptions, app).listen(port, () => {
  console.log('server running at ' + port)
})
  • Open https://localhost:3000 in Google Chrome and you'll see that it's not secure. Yet!
  • In Developer Tools > Security > View Certificate: Drag image to your desktop and double click it.
  • Click 'Add'
  • Find it in Keychain Access and double click it
  • Expand 'Trust' and change 'When using this certificate' to 'Always trust'.
  • You may be prompted to authenticate.
  • Restart your server.
  • Refresh your browser.
  • Enjoy! :)

Examples related to node.js

Hide Signs that Meteor.js was Used Querying date field in MongoDB with Mongoose SyntaxError: Cannot use import statement outside a module Server Discovery And Monitoring engine is deprecated How to fix ReferenceError: primordials is not defined in node UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib error running php after installing node with brew on Mac internal/modules/cjs/loader.js:582 throw err DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server Please run `npm cache clean`

Examples related to express

UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block jwt check if token expired Avoid "current URL string parser is deprecated" warning by setting useNewUrlParser to true MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017] npm notice created a lockfile as package-lock.json. You should commit this file Make Axios send cookies in its requests automatically What does body-parser do with express? SyntaxError: Unexpected token function - Async Await Nodejs Route.get() requires callback functions but got a "object Undefined" How to redirect to another page in node.js

Examples related to openssl

dyld: Library not loaded: /usr/local/opt/openssl/lib/libssl.1.0.0.dylib How to install OpenSSL in windows 10? SSL_connect: SSL_ERROR_SYSCALL in connection to github.com:443 How to fix: fatal error: openssl/opensslv.h: No such file or directory in RedHat 7 Homebrew refusing to link OpenSSL Solving sslv3 alert handshake failure when trying to use a client certificate How to install latest version of openssl Mac OS X El Capitan How to resolve the "EVP_DecryptFInal_ex: bad decrypt" during file decryption SSL error SSL3_GET_SERVER_CERTIFICATE:certificate verify failed Can't get private key with openssl (no start line:pem_lib.c:703:Expecting: ANY PRIVATE KEY)

Examples related to localhost

Xampp localhost/dashboard Set cookies for cross origin requests Invalid Host Header when ngrok tries to connect to React dev server How to turn on/off MySQL strict mode in localhost (xampp)? What is IPV6 for localhost and 0.0.0.0? How do I kill the process currently using a port on localhost in Windows? How to run html file on localhost? Can't access 127.0.0.1 Server http:/localhost:8080 requires a user name and a password. The server says: XDB How to solve ERR_CONNECTION_REFUSED when trying to connect to localhost running IISExpress - Error 502 (Cannot debug from Visual Studio)?

Examples related to ssl-certificate

How to install OpenSSL in windows 10? Scraping: SSL: CERTIFICATE_VERIFY_FAILED error for http://en.wikipedia.org Not able to install Python packages [SSL: TLSV1_ALERT_PROTOCOL_VERSION] Letsencrypt add domain to existing certificate javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure bypass invalid SSL certificate in .net core How to add Certificate Authority file in CentOS 7 How to use a client certificate to authenticate and authorize in a Web API This certificate has an invalid issuer Apple Push Services iOS9 getting error “an SSL error has occurred and a secure connection to the server cannot be made”