The process of validating input data is important to avoid security issues or application errors due to malicious intentions by users. It’s essential that you never trust user data, because there’s always the one user that just wants to test if your application has the security glitch and only wants to test the XSS they previously read about …
Validating the user input also applies to path parameters and within this tutorial you’ll make use of joi for that use case.
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
Prepare Your Project and Install Joi
You’ll use the joi
module for object schema validation from within hapi’s plugin ecosystem to validate one or many path parameters. Before defining the validation itself, you need to add joi
as a dependency to your project:
npm i -S joi
Installation process finished successfully? Your project is ready to make use of joi
for input validation.
Use Joi for Path Parameter Validation
Path parameters are configured within the route setup of your hapi server. While adding various routes, you’re already defining different types of path parameters, like optional or wildcard parameters.
While adding individual routes, you can also apply the validation that should be used for any request that hits the related endpoint. The following code snippet illustrates the actual validation configuration.
In case you’ve path parameter validation in place, hapi applies the defined constraints. Depending on whether the given path parameter data passes the validation process successfully, the request will be proceeded by calling the route handler. If validation fails, hapi will reply with a detailed boom error object including the reason why validation went south.
var Joi = require('joi')
server.route({
method: 'GET',
path: '/tutorials/page/{page}',
config: {
handler: …function (request, reply) {
reply('Hello Future Studio')
}
validate: {
params: {
page: Joi.number().min(1)
}
}
}
})
Within the code block above, you can see how to apply validation by defining a configuration object for config.validate
within your route. To validate path parameters, provide each path parameter within a params
object. And within that object, the property name represents the path parameter name and its value contains the actual joi
validation constraints.
You can find all applicable methods and constraints within joi
’s API reference.
Notice: if you apply validation to one of your path parameters, you need to provide the validation configuration for all other parameters as well.
Outlook
This tutorial walked you through the setup of path parameter validation for a given route by applying constraints using joi
. You should never trust provided data from your users and always make sure the input is validated against a set of rules that make sure your server won’t get compromised.
Please keep in mind, that you need to define the validation for each of your parameters and you can’t just pick your favorites. Joi won’t allow only a subset of path parameters to be validated.
Are you looking for a guide to deploy your hapi apps in a zero-downtime manner? Follow the link!
Do you have a question or comment that you would like to ask or share? Please don’t hesitate to leave a comment below or tweet us on Twitter @futurestud_io.
Make it rock & enjoy coding!