Skip to content

Express with SSL example #4680

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions examples/ssl/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
**/*.pem
14 changes: 14 additions & 0 deletions examples/ssl/Readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# Express server with SSL enabled

Please create the self-signed certificate and private key to path `/certs` by following command:

```bash
./create_certs.sh
```

When running this example, the application runs on

* https://localhost:8443

and asks the user to make a security exception in the browser in order to see the pages.
CAUTION: *Self-signed certificates should never be used in production environments!*
5 changes: 5 additions & 0 deletions examples/ssl/create_certs.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
#!/bin/bash

mkdir -p certs && \
cd certs && \
openssl req -x509 -newkey rsa:4096 -nodes -sha256 -subj '/CN=localhost' -days 3650 -keyout key.pem -out cert.pem
41 changes: 41 additions & 0 deletions examples/ssl/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
/**
* Module dependencies.
*/

var express = require('../..');
var fs = require('fs');
var path = require('path');
var https = require('https');

var app = module.exports = express();

app.use(function(req, res) {
res
.set('Content-Type', 'text/html;charset=utf-8')
.status(200)
.send('<h1>Hello world from a SSL-enabled server!</h1>')
.end();
});

/* istanbul ignore next */
if (!module.parent) {
try {
/* These certificates should be created manually as specified in the
* Readme.md */
var certsPath = path.join(__dirname, 'certs');
var options = {
key: fs.readFileSync(path.join(certsPath, 'key.pem')),
cert: fs.readFileSync(path.join(certsPath, 'cert.pem'))
};

/* Instead of using app.listen() directly, you should create a regular
* Node.js HTTPS server and place the Express server as its only midware. */
var httpsServer = https.createServer(options, app);
var PORT = 8443;
httpsServer.listen(PORT, function() {
console.log('SSL Express server responds in https://localhost:' + PORT);
});
} catch(er) {
console.error('Please create the certificates manually first according to the Readme.md.');
}
}