Handling request headers isn’t a use case that comes to mind immediately when thinking through the development process of your app. You might think of routes, requests, appropriate responses and the design of your views. And at some point, you’re in a more advanced development stage and see the benefit of using request headers for a given task.
In this tutorial, you’ll learn how to access and handle HTTP headers that are sent with your request.
Before moving on with request headers in hapi, have a look at other tutorials within this in-depth series.
hapi Series Overview
- What You’ll Build
- Prepare Your Project: Stack & Structure
- Environment Variables and Storing Secrets
- Set Up MongoDB and Connect With Mongoose
- Sending Emails in Node.js
- Load the User’s Profile Picture From Gravatar Using Virtuals in Mongoose
- Implement a User Profile Editing Screen
- Generate a Username in Mongoose Middleware
- Displaying Seasons and Episodes for TV Shows with Mongoose Relationship Population
- Implementing Pagination for Movies
- Implement a Watchlist
- Create a Full Text Search with MongoDB
- Create a REST API with JSON Endpoints
- Update Mongoose Models for JSON Responses
- API Pagination for TV Shows
- Customize API Endpoints with Query Parameters
- Always Throw and Handle API Validation Errors
- Advanced API Validation With Custom Errors
- Create an API Documentation with Swagger
- Customize Your Swagger API Documentation URL
- Describe Endpoint Details in Your Swagger API Documentation
- 10 Tips on API Testing With Postman
- JWT Authentication in Swagger API Documentation
- API Versioning with Request Headers
- API Login With Username and Password to Generate a JWT
- JWT Authentication and Private API Endpoints
- Refresh Tokens With JWT Authentication
- Create a JWT Utility
- JWT Refresh Token for Multiple Devices
- Check Refresh Token in Authentication Strategy
- Rate Limit Your Refresh Token API Endpoint
- How to Revoke a JWT
- Invalidate JWTs With Blacklists
- JWT Logout (Part 1/2)
- JWT “Immediate” Logout (Part 2/2)
- A Better Place to Invalidate Tokens
- How to Switch the JWT Signing Algorithm
- Roll Your Own Refresh Token Authentication Scheme
- JWT Claims 101
- Use JWT With Asymmetric Signatures (RS256 & Co.)
- Encrypt the JWT Payload (The Simple Way)
- Increase JWT Security Beyond the Signature
- Unsigned JSON Web Tokens (Unsecured JWS)
- JWK and JWKS Overview
- Provide a JWKS API Endpoint
- Create a JWK from a Shared Secret
- JWT Verification via JWKS API Endpoint
- What is JOSE in JWT
- Encrypt a JWT (the JWE Way)
- Authenticate Encrypted JWTs (JWE)
- Encrypted and Signed JWT (Nested JWT)
- Bringing Back JWT Decoding and Authentication
- Bringing Back JWT Claims in the JWT Payload
- Basic Authentication With Username and Password
- Authentication and Remember Me Using Cookies
- How to Set a Default Authentication Strategy
- Define Multiple Authentication Strategies for a Route
- Restrict User Access With Scopes
- Show „Insufficient Scope“ View for Routes With Restricted Access
- Access Restriction With Dynamic and Advanced Scopes
- hapi - How to Fix „unknown authentication strategy“
- Authenticate with GitHub And Remember the Login
- Authenticate with GitLab And Remember the User
- How to Combine Bell With Another Authentication Strategy
- Custom OAuth Bell Strategy to Connect With any Server
- Redirect to Previous Page After Login
- How to Implement a Complete Sign Up Flow With Email and Password
- How to Implement a Complete Login Flow
- Implement a Password-Reset Flow
- Views in hapi 9 (and above)
- How to Render and Reply Views
- How to Reply and Render Pug Views (Using Pug 2.0)
- How to Create a Dynamic Handlebars Layout Template
- Create and Use Handlebars Partial Views
- Create and Use Custom Handlebars Helpers
- Specify a Different Handlebars Layout for a Specific View
- How to Create Jade-Like Layout Blocks in Handlebars
- Use Vue.js Mustache Tags in Handlebars Templates
- How to Use Multiple Handlebars Layouts
- How to Access and Handle Request Payload
- Access Request Headers
- How to Manage Cookies and HTTP States Across Requests
- Detect and Get the Client IP Address
- How to Upload Files
- Quick Access to Logged In User in Route Handlers
- How to Fix “handler method did not return a value, a promise, or throw an error”
- How to Fix “X must return an error, a takeover response, or a continue signal”
- Query Parameter Validation With Joi
- Path Parameter Validation With Joi
- Request Payload Validation With Joi
- Validate Query and Path Parameters, Payload and Headers All at Once on Your Routes
- Validate Request Headers With Joi
- Reply Custom View for Failed Validations
- Handle Failed Validations and Show Errors Details at Inputs
- How to Fix AssertionError, Cannot validate HEAD or GET requests
Access Request Headers
Every request that touches your server contains a ton of client information, like HTTP method, the request URL, payload, query and path parameters.
Further, the request also includes HTTP headers that are of interest in specific situations, like pagination or checking if the request went through a (reverse) proxy, like nginx. Well, there are multiple scenarios where request headers are a very suitable use case to transmit data with the client request. For example, GitHub uses request headers to allow developers paginate through individual API endpoints.
Alright, the following snippet illustrates how to get access to the request headers in hapi.
hapi v17
server.route({
method: 'GET',
path: '/',
handler: (request, h) {
var headers = request.headers // <-- this is the important line
// use of individual header values for data processing
return { your: data }
}
})
hapi v16
server.route({
method: 'GET',
path: '/',
handler: function (request, reply) {
var headers = request.headers // <-- this is the important line
// use of individual header values for data processing
reply({ your: data })
}
})
The snippet is reduced to the route definition and the interesting part is the route handler. Within the route handler, you’ve access to the request
object and that includes the headers
.
request.headers
returns an object of key-value-pairs, like
{
host: 'localhost:3000',
connection: 'keep-alive',
'cache-control': 'max-age=0',
'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) …',
'accept-encoding': 'gzip, deflate, sdch, br'
}
As you can see, the keys differ in their form, like the first two (host
and connection
) are without quotes and the others is wrapped in single quotes. The quotes are required due to the dashes in-between the key’s words.
You can access individual fields like this:
var host = request.headers.host
var cacheControl = request.headers[ 'cache-control' ]
// do further processing with the host and cache control values
That’s all the magic behind request headers in hapi.
Notice: you need to keep an eye on the format of the header key and depending on wrapping quotes, you need to access the related value differently.
Outlook
This tutorial walked you through the handling request headers and showed you that individual keys may be formatted differently. Further, you know how to access the values of headers fields, even though they are or aren’t wrapped in quotes.
Have a question or thought in mind? Please don’t hesitate to leave a comment or tweet us @futurestud_io.
Make it rock & enjoy coding!