Node.js — HTTPS
HTTPS Server
const https = require('https');
const fs = require('fs');
const options = {
key: fs.readFileSync('private-key.pem'),
cert: fs.readFileSync('certificate.pem')
};
const server = https.createServer(options, (req, res) => {
res.writeHead(200);
res.end('Secure Hello!\n');
});
server.listen(443);
Making HTTPS Requests
const https = require('https');
https.get('https://api.example.com/data', (res) => {
let data = '';
res.on('data', chunk => data += chunk);
res.on('end', () => console.log(JSON.parse(data)));
});
SSL Certificates
| Type | Description |
|---|---|
| Self-signed | For development |
| Let's Encrypt | Free production certs |
| Commercial | Paid certificates |
Self-Signed Certificate
openssl req -x509 -newkey rsa:2048 -nodes -sha256 \
-subj '/CN=localhost' \
-keyout localhost-privkey.pem \
-out localhost-cert.pem
Environment Variables
const options = {
key: fs.readFileSync(process.env.SSL_KEY),
cert: fs.readFileSync(process.env.SSL_CERT)
};
Mini Practice
- Create an HTTPS server
- Generate self-signed certificates
- Make HTTPS requests
- Configure SSL environment
Up Next
Continue with Streams — processing data streams.
Related Topics
Frequently Asked Questions about HTTPS
What is HTTPS in Node.js?
HTTPS is a fundamental concept in Node.js. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn HTTPS?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn HTTPS.
Why is HTTPS important in Node.js?
HTTPS is essential for Node.js development. Understanding this concept will help you write better code and solve real-world problems more effectively.