The latest version of the Alexa Skills Kit Software Development Kit (SDK) for Node.js includes many improvements to request handling, response building, and attribute management. In this post, we will dive deeper into a brand new feature of the SDK: the request and response interceptors.
Request and response interceptors are special functions that are processed immediately before and after intent handler functions are executed. You can use these interceptor functions to invoke common logic that applies to multiple incoming requests or outgoing responses. Centralizing common logic helps you avoid duplicating code and promotes the DRY (Don’t Repeat Yourself) principle of software development.
Request interceptors are invoked immediately before the execution of the selected handler for an incoming request. You can use them to add any logic that needs to be performed for each request, irrespective of the type of request.
Response interceptors are invoked immediately after execution of the selected request handler. Because response interceptors have access to the output generated from execution of the request handler, they are ideal for tasks such as response sanitization, internationalization, and validation.
There are two steps to using the request and response interceptors:
One thing to note is that just like the regular request handlers, request and response interceptors are passed a HandlerInput instance when invoked. In addition to this, the response interceptors have access to the Optional<Response> produced by the RequestHandler.
The HandlerInput exposes various entities useful in request processing, and includes the following:
Because you have access to the entire request received and also the attributes, you can use the interceptors to access and alter them. Here are a few examples of how you can use the request and response interceptors to centralize common logic.
For debugging purposes, you may want to log the JSON request to Amazon CloudWatch each time a request is received by your skill. You can do this by simply including a console.log() statement inside your request interceptor. This console.log statement will get fired each time a request is received by your skill, just before the control is handed to the relevant intent handler.
Here’s how you would do that using the request interceptor:
Step 1: Set Up the Request Interceptor Function
const RequestLog = {
process(handlerInput) {
console.log("REQUEST ENVELOPE = " + JSON.stringify(handlerInput.requestEnvelope));
return;
}
};
Step 2: Register the Request Interceptor
Much like the request handlers, you would then register your request interceptors by adding them to the skill builder by using `.addRequestInterceptors(NameOfTheRequestInterceptorFunction)`. So, like -
const skill = Alexa.SkillBuilders.custom()
.addRequestHandlers(LaunchRequestHandler,
GetNewFactIntentHandler)
.addRequestInterceptors(RequestLog)
.lambda()
Here’s an example of the City Guide Skill using the request interceptor to find the customer’s locale. Since the City Guide Skill uses the customer’s locale to offer local recommendations, we include the logic of finding the locale in our request interceptor. The interceptor is executed each time a request is received immediately before the control is handed to the relevant intent handler, which in this case could be LunchHandler, BreakfastHandler, CoffeeHandler, etc.
Step 1: Set Up the Request Interceptor Function
// Finding the locale of the user
const LocalizationInterceptor = {
process(handlerInput) {
const localizationClient = i18n.use(sprintf).init({
lng: handlerInput.requestEnvelope.request.locale,
overloadTranslationOptionHandler: sprintf.overloadTranslationOptionHandler,
resources: languageStrings,
returnObjects: true
});
const attributes = handlerInput.attributesManager.getRequestAttributes();
attributes.t = function (...args) {
return localizationClient.t(...args);
};
},
};
Step 2: Register the Request Interceptor
The City Guide Skill then registers this request interceptor with `.addRequestInterceptors(LocalizationInterceptor)` as shown below:
const skillBuilder = Alexa.SkillBuilders.custom();
exports.handler = skillBuilder
.addRequestHandlers(
LaunchHandler,
AboutHandler,
CoffeeHandler,
. . .
. . .
. . .
SessionEndedHandler
)
.addRequestInterceptors(LocalizationInterceptor)
.addErrorHandlers(ErrorHandler)
.lambda();
Here’s an example of a response interceptor that handles saving persistent attributes to a database before the response is sent back to Alexa.
Step 1: Set Up the Response Interceptor Function
const PersistenceSavingResponseInterceptor = {
process(handlerInput) {
return new Promise((resolve, reject) => {
handlerInput.attributesManager.savePersistentAttributes()
.then(() => {
resolve();
})
.catch((error) => {
reject(error);
});
});
}
};
Step 2: Register the Response Interceptor
Much like the request interceptors, you would register the response interceptors by adding them to the skill builder by using `.addResponseInterceptors(NameOfTheResponseInterceptorFunction)`. So, like -
const skill = Alexa.SkillBuilders.custom()
.addRequestHandlers(LaunchRequestHandler,
GetNewFactIntentHandler)
.addRequestInterceptors(RequestLog)
.addResponseInterceptors(PersistenceSavingResponseInterceptor)
.lambda()
There are several other ways you can use these functions. You can create a request interceptor that initializes skill attributes for new sessions before request handlers are executed. Request attributes provide a way for request interceptors to pass data and entities on to request handlers. The request interceptors are also useful for adding data to the request attributes and to find the locale of the user. Use response interceptors to validate data.
We can’t wait to see what you build using the new SDK. If you have questions, find me on Twitter @amit. For any issues with the SDK, please consider submitting a pull request through the GitHub repo.
When you create delightful skills with compelling content, customers win. You can make money through Alexa skills using in-skill purchasing or Amazon Pay for Alexa Skills. You can also make money for eligible skills that drive some of the highest customer engagement with Alexa Developer Rewards. Learn more about how you can make money with Alexa skills, and download our guide to learn which product best meets your needs.