/

How to Generate a Local SSL Certificate

How to Generate a Local SSL Certificate

Note: The commands provided in this blog post were tested on macOS. They should work similarly on Linux, but I cannot guarantee their effectiveness on Windows.

To generate a local SSL certificate, follow these steps:

  1. Open the terminal and navigate to the root folder of your project.

  2. Run the following OpenSSL command to generate a self-signed certificate and private key:

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

    This command generates two files: cert.pem (the certificate) and keytmp.pem (the temporary key).

  3. Convert the temporary key to a readable format using the following OpenSSL command:

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

    This will create a new file named key.pem which contains the readable private key.

  4. With Express/Node.js, you can load the generated certificate and key by adding the following code to your application:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    const fs = require('fs');
    const https = require('https');
    const app = express();

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

    https.createServer({
    key: fs.readFileSync('key.pem'),
    cert: fs.readFileSync('cert.pem')
    }, app).listen(3000, () => {
    console.log('Listening...');
    });

    Make sure to replace app.get('/', ...) with your actual route handler code.

  5. If you are using create-react-app, you need to modify the start script in the package.json file. Update it as follows:

    1
    "start": "export HTTPS=true && SSL_CRT_FILE=cert.pem && SSL_KEY_FILE=key.pem react-scripts start"

    This ensures that the React development server uses the generated SSL certificate and key.

Please consult the documentation of your specific framework or library for instructions on how to pass the certificate and key to your application.

Tags: SSL certificate, local development, OpenSSL, Express, Node.js, create-react-app