ExpressJS Series: What I need to know about the req Request Object in the Route Request Handler

Ganesh B
8 min readOct 1, 2018

--

In the previous blog, we saw how routes can be set up in an ExpressJS project. In this blog we will look at what all can be captured in the request object to make your application run and be sturdy based on the request sent by the client.

REQUEST OBJECT PROPERTIES

There are a lot things you can access in the route handler from the request object. It mainly takes care of the keeping track of all the information of the request so that you can know, verify, validate, clean, allow, block, process, authenticate in order to send back appropriate responses. You can very easily capture everything that is there in the request object by just consoling out the req object.

console.log(req);

Here is the list:

req.app, req.baseUrl, req.body, req.cookies, req.fresh, req.hostname, req.ip, req.ips, req.method, req.originalUrl, req.params, req.path, req.protocol, req.query,req.route, req.secure, req.signedCookies, req.stale, req.subdomains, req.xhr

All of the following object’s values can be captured by consoling out like below:

console.log(req.yourDefinition)

We will be getting into a lot of details for each of these sections since working with some of them can be tricky; but some basic important information about them are as below:

req.app : This is the object that holds the reference to the ExpressJS application reference. Very useful when you want to access anything thats part of the application to do some specific processing either in the middleware or in the business logic.

req.baseUrl : This gives you access to the base URL of the application with which you are working and got a request to.

Usage: = req.baseUrl

req.body : This gives you the access to the content that is sent to the server in a request by the user/client application. This is sent as buffer data. You have to parse and understand the contents based on the content-type of the data for the body to be useful. We will use a package that will help us with that.

Usage: = req.body

Code Sample:

req.cookies : If you want to identify, track user, or store information of some application state then it can done using cookies. The information about cookies are stored in this object. If there are no cookies sent, then it will be a plain empty javascript object {}.

Usage: = req.cookie.cookieKeyName

Code Sample:

req.fresh : This is a boolean value. This is opposite of req.stale. It is true, if (1) cache-control request header doesn’t have a no-cache directive, or if (2) The if-modified-since request header is specified and last-modified request header is equal to or earlier than the modified response header, or if (3) the if-none-match request header is *, or if (4) the if-none-match request header, after being parsed into its directives, does not match the etag response header. This is the official definition of req.fresh. We will look into it in a lot more detail in a different post after we have looked into Headers of a request post that I intend to cover soon.

Usage: = req.fresh

Code Sample:

req.hostname : This refers to the hostname of the request server and is derived from the HTTP header of the request. This is a very important parameter is the one which helps us to differentiate requests, and to add very important features to the application based on which hostname the request is coming from. This along with some others attract a lot of infrastructure security and application security professionals for obvious reasons.

Usage: = req.hostname

Code Sample:

req.ip : This helps to get the IP Address of the server/client from where the request was made.

Usage: = req.ip

Code Sample:

req.ips : req.ips is an array of IPs containing the list of client IPs the request has been forwarded/received from. The need arises since there are a lot of times when your server is behind a proxy or receives requests indirectly from different internal hosts. In such cases, req.ip is incapable of providing you the actual request client’s information. Hence, proxies or such redirect hosts set a X-Forwarded-For header in the request for the server to have some information about the client.

Usage: = req.ips

Code Sample:

req.ips can be set by the client, re-directer, or the proxy. Remember, this IP set or IP Addresses can be easily spoofed, and unreliable for the same reason. But an attempt can definitely be made by ExpressJS; and it uses the trust proxy package to determine the forwarding set of IPs to determine the client. When the trust proxy setting evaluates to true, you can expect an IP Address or set of IP Addresses as an array in req.ips. Read more about it here in app.settings. The links can change so remember to look for trust proxy details in the app.settings of ExpressJS documentation, if needed.

req.method : We have been talking about this quite. req.method provides you the details of the request HTTP method — GET, POST, PUT, etc.

Usage: = req.method

Code Sample:

req.url : This is the URL or path of the server the original request was made to. req.url can be accessed and might not be documented in ExpressJS since it is not a property of ExpressJS but has been inherited from the NodeJS’s HTTP Module.

Usage: = req.url

req.originalUrl : This is the URL or path of the server the original request was made to, similar to request.url, but this retains the original URL the request was made to. This is made available so that you can use it manipulate it or rewrite it or use it for any internal routing purposes. It contains the entire path of the request and includes the dynamic URL parameters and query parameters in it.

Usage: = req.originalUrl

req.params : We have talked about this before. The request dynamic URL based parameters are available here. Very helpful, and commonly used or accessed object during application logic development.

Usage: = req.params

Code Sample:

req.path : This contains the request path portion of the request URL.

Usage:= req.path

Now, there seems to be a small confusion on what to use for accessing URL, what the purpose is to have multiple options for URL string access, and what the value results in while accessing. Have a look at the following code example from ExpressJS that nicely demonstrates the difference between them (req.originalUrl, req.baseUrl, req.path):

req.originalUrl, req.baseUrl, req.path Difference

I cannot think of a better differentiation code. You might notice that each them are subtly different from the other. Most often than not, these object options are accessed by your application middlewares or business logic functions that you call with/within your route handler.

req.protocol : This contains the protocol of the request : HTTP or TLS/HTTPS respectively depending on the request. Remember, When the trust proxy setting is true, this property will use the value of the X-Forwarded-Proto header field if present. This X-Forwarded-Proto header can be set by the client or by the proxy. Can be helpful in deciding a course of action for the request based on protocol.

Usage: = req.protocol

Code Sample:

req.query : We have seen and worked with this before and it provides you with the query parameters in the URL, if they are there.

Usage: = req.query

Code Sample:

req.route : Contains details of the entire route that is being handled. It contains details of the path, route handler, its name, methods, params. If you have a generic route handler, working with a middlewares, or application dependant business logic this can be quite a helpful information. You might not need this quite often otherwise during simple route handlers since other request objects solves the purpose of it.

Usage: = req.route

Code Sample (from ExpressJS Documentation):

Console out is somewhat like below:

{ path: '/user/:id?',
stack:
[ { handle: [Function: userIdHandler],
name: 'userIdHandler',
params: undefined,
path: undefined,
keys: [],
regexp: /^\/?$/i,
method: 'get' } ],
methods: { get: true } }

req.secure : Boolean value (true/false) based on whether it is a TLS/HTTPS protocol or not.

Usage: = req.secure

Code Sample:

req.signedCookies : This is available to you only if you use the cookie parser library. Helps you work with a better tamper proof cookie handling with privately signed secret.

Usage: = req.signedCookies

req.stale : This is the opposite of req.fresh.

req.subdomains : Array of subdomains of the request.

// HEADERS
// Host: “my.requesting.domain.example.com”
// => [“my”, “requesting”, “domain”]

req.xhr : Boolean value (true/false) based on whether the X-Requested-With Header field is XMLHttpRequest; indicating a library use from the client side.

Usage: = req.xhr

REQUEST OBJECT METHODS

Apart from the properties we saw, there a few functions inside the ExpressJS object that helps you access request details easily. It includes accessing details like Headers - Encodings, Languages, Character sets, Content-Type requested in response (Accepts), etc.

req.accepts() : Based on the Accept Header in the request, this function checks and returns whether a response content-type from the server is possible. If the Accept does not match or if the decided response content-type is not compatible you will get a false as the return value of the function and you can send back an error (with 406, “Not Acceptable”) to the client.

Usage: = req.accepts([… String array options …]);

Code Sample:

The order of array is important. Provide the server preferred option in start/beginning of the array.

req.acceptsCharsets() : Based on specified character sets set in the request Header Accept-Charset, it responds with the first matching value. If no match found then it returns false. The req.accepts() example applies here for usage.

Usage: = req.acceptsCharsets([… Character Set Server Options as string array …]);

req.acceptsEncodings() : Based on specified encodings set in the request Header Accept-Encoding, it responds with the first matching value. If no match found then it returns false.

Usage: = req.acceptsEncodings([… Encoding Server Options as string array …]);

req.acceptsLanguages() : Based on specified languages set in the request Header Accept-Language, it responds with the first matching value. If no match found then it returns false.

Usage: = req.acceptsLanguages([… Server Language Options as string array …]);

These methods actually come from the ExpressJS internal sub-package jshttp/accepts. We will discuss this package separately in a post. There definitely are use cases for this package which are commonly implemented in applications, one like handling multiple response content-type namely json, xml, text, etc.

req.header() : This helps you get the sent Headers of the client request. This is a generic function that allows you to access any header sent in the request by providing the name/key of the header. This is an alias for req.get. Look at the code below:

Usage: = req.header(HeaderKeyName);

Code Sample:

req.get() : This is an alias to req.header and the usage is exactly the same.

Usage: = req.get(HeaderKeyName);

Code Sample:

req.is() : This method results in a Boolean return type value (true/false) based on whether the content-type in the Header is of a specific type.

Usage: = req.is(contentTypeValue);

Code Sample:

req.range() : This gives the value based on specified maximum Size of the resource.

Usage: = req.range(Size, Options);

Code Sample (taken from ExpressJS documentation):

In the next blog, we will learn what middlewares are, how to create them, and work with them. In the process, we will also use some of the above request object parameters and methods and talk about some libraries that ease the job of creating a secure, scalable, working ExpressJS server.

Working with Middlewares: https://medium.com/@ganeshsurfs/expressjs-series-working-with-middlewares-5fa530c4e4e5

ExpressJS Series — All Blogs https://medium.com/@ganeshsurfs/expressjs-series-links-9e038be8d78b

Let me know how I did, and if you learnt something new. Do leave your comments, and dont forget to like the article.

--

--