0
0
Expressframework~5 mins

HTTPS and SSL certificates in Express

Choose your learning style9 modes available
Introduction

HTTPS keeps websites safe by encrypting data between the user and the server. SSL certificates prove the website is trustworthy.

When you want to protect user passwords and personal info on your website.
When you need to secure online payments or sensitive transactions.
When you want your website to show a padlock icon in browsers for trust.
When you want to improve your website's search engine ranking.
When you want to prevent others from spying on your website traffic.
Syntax
Express
const https = require('https');
const fs = require('fs');
const express = require('express');

const app = express();

const options = {
  key: fs.readFileSync('path/to/private.key'),
  cert: fs.readFileSync('path/to/certificate.crt')
};

https.createServer(options, app).listen(443, () => {
  console.log('HTTPS server running on port 443');
});

The key is your private SSL key file.

The cert is your SSL certificate file from a trusted authority.

Examples
Basic SSL options with key and certificate files.
Express
const options = {
  key: fs.readFileSync('server.key'),
  cert: fs.readFileSync('server.crt')
};
Starts HTTPS server on default secure port 443.
Express
https.createServer(options, app).listen(443);
Simple route to test HTTPS server response.
Express
app.get('/', (req, res) => {
  res.send('Hello secure world!');
});
Sample Program

This program creates a secure HTTPS server using Express. It reads SSL key and certificate files, sets up a simple route, and listens on port 443. When you visit the site, you see a secure connection and the message.

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

const app = express();

const options = {
  key: fs.readFileSync('server.key'),
  cert: fs.readFileSync('server.crt')
};

app.get('/', (req, res) => {
  res.send('Welcome to the secure server!');
});

https.createServer(options, app).listen(443, () => {
  console.log('HTTPS server running on port 443');
});
OutputSuccess
Important Notes

SSL certificates must be from a trusted authority or browsers will warn users.

Use port 443 for HTTPS to avoid specifying the port in the URL.

Keep your private key file secure and never share it.

Summary

HTTPS encrypts data to keep it safe between users and servers.

SSL certificates prove your website is secure and trusted.

Express can create HTTPS servers by providing SSL key and certificate files.