Express.js – req.secure Property


The req.secure property returns a Boolean value that returns true if a TLS connection is established, else it will return False.

Its logic is similar to the following method −

--> req.protocol == "https"

Syntax

req.secure

Example 1

Create a file with the name "reqSecure.js" and copy the following code snippet. After creating the file, use the command "node reqSecure.js" to run this code as shown in the example below −

// req.secure Property Demo Example

// Importing the express
var express = require('express');

// Initializing the express and port number
var app = express();

// Initializing the router from express
var router = express.Router();
var PORT = 3000;

// Defining an endpoint
app.get('/api', function (req, res) {
   console.log(req.secure);
   res.end(req.secure);
});

app.listen(PORT, function(err){
   if (err) console.log(err);
   console.log("Server listening on PORT", PORT);
});

Hit the following Endpoint with a GET request: http://localhost:3000/api

Output

C:\home
ode>> node reqSecure.js Server listening on PORT 3000 false

Example 2

Let's take a look at one more example.

// req.secure Property Demo Example

// Importing the express
var express = require('express');

// Initializing the express and port number
var app = express();

// Initializing the router from express
var router = express.Router();
var PORT = 3000;

// Defining an endpoint
app.get('/api', function (req, res) {
   if (req.secure) {
      console.log("Secured Connection")
      res.end();
   } else {
      console.log("Connection is Not Secured");
      res.end();
   }
});

app.listen(PORT, function(err){
   if (err) console.log(err);
   console.log("Server listening on PORT", PORT);
});

Hit the following Endpoint with a GET request − http://localhost:3000/api

Output

C:\home
ode>> node reqSecure.js Server listening on PORT 3000 Connection is Not Secured

Updated on: 28-Mar-2022

158 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements