DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Alexa Skill With TypeScript
  • Alexa Skill With Python
  • Alexa Skill With Local DynamoDB
  • The Future of Rollouts: From Big Bang to Smart and Secure Approach to Web Application Deployments

Trending

  • DGS GraphQL and Spring Boot
  • The Cypress Edge: Next-Level Testing Strategies for React Developers
  • MySQL to PostgreSQL Database Migration: A Practical Case Study
  • Ethical AI in Agile
  1. DZone
  2. Coding
  3. Tools
  4. Alexa Skill With Node.js

Alexa Skill With Node.js

By 
Xavier Portilla Edo user avatar
Xavier Portilla Edo
DZone Core CORE ·
Updated Apr. 20, 20 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
21.6K Views

Join the DZone community and get the full member experience.

Join For Free

Alexa Skills can be developed using Alexa Lambda functions or a REST API endpoint. Lambda function is Amazon's implementation of serverless functions available in AWS. Amazon recommends using Lambda functions despite the fact that they are not easy to debug. While you can log to a CloudWatch log, you can't hit a breakpoint and step into the code.

This makes live debugging of Alexa requests a very hard task. In this post, we will implement a custom Skill for Amazon Alexa by using Node.js, npm, and AWS Lambda Functions. This Skill is basically a "Hello World" example. With this post, you will be able to create a custom Skill for Amazon Alexa, implement functionality by using Node.js, and start your custom skill both from your local computer and from AWS. This post contains materials from different resources that can be seen in the Resources section.

Prerequisites

Here are the technologies used in this project:

  1. Amazon Developer Account - How to get it.
  2. AWS Account - Sign up here for free.
  3. ASK CLI - Install and configure ASK CLI.
  4. Node.js v10.x.
  5. Visual Studio Code.
  6. npm Package Manager.
  7. Alexa ASK for Node.js (Version >2.7.0).
  8. ngrok.

The Alexa Skills Kit Command Line Interface (ASK CLI) is a tool for you to manage your Alexa skills and related resources, such as AWS Lambda functions. With ASK CLI, you have access to the Skill Management API, which allows you to manage Alexa skills programmatically from the command line. We will use this powerful tool to create, build, deploy and manage our "Hello World" Skill. Let's start!

Creating the Skill With ASK CLI

For creating the Alexa Skill, we will use de ASK CLI previously configured. First of all, we have to execute this command:

Shell
 




xxxxxxxxxx
1


 
1
ask new



This command will run and interactive step-by-step creation process:

  1. The first thing the ASK CLI is going to ask us is the runtime of our Skill. In our case, Node.js v10:

Setting Skill runtime

The second step is the template that our Skill is based on. In our case, we will select the Hello World template:

Selecting Hello World template

Finally, the ASK CLI is going to ask us for the name of the Skill:

Adding name of our Skill

Project Files

These are the main files of the project:

Shell
 




xxxxxxxxxx
1
18


 
1
    ├───.ask
2
    │       config
3
    │
4
    ├───.vscode
5
    │       launch.json
6
    ├───hooks
7
    ├───lambda
8
    │   └───custom
9
    │         ├───errors
10
    │         ├───intents
11
    │         ├───interceptors
12
    │         ├───utilities
13
    │         ├─── index.js
14
    │         ├─── local-debugger.js
15
    │         └─── package.json
16
    ├───models
17
    │       es-ES.json
18
    └───skill.json



  • .ask: Folder which contains the ASK CLI's config file. This config files will remain empty until we execute the command ask deploy
  • .vscode/launch.json: Launch preferences to run locally your Skill for local testing. This setting launch lambda/custom/local-debugger.js. This script runs a server on http://localhost:3001 for debug the Skill.
  • hooks: A folder that contains the hook scripts. Amazon provides two hooks, post_new_hook and pre_deploy_hook.
    • post_new_hook: executed after the Skill creation. Inn Node.js runs npm install in each sourceDir in skill.json
    • pre_deploy_hook: executed before the Skill deployment. In Node.js runs npm install in each sourceDir in skill.json as well.
  • lambda/custom: A folder that contains the source code for the skill's AWS Lambda function:
    • index.js: the lambda main entry point.
    • utilities/languageStrings.js: i18n dictionaries used by the library i18next, which allows us to run the same Skill in different configuration languages.
    • package.json: this file is core to the Node.js ecosystem and is a basic part of understanding and working with Node.js, npm, and even modern JavaScript
    • utilities/util.js: file with helpful functions.
    • local-debugger.js: used for debug our skill locally.
    • errors: folder that contains all Error handlers.
    • intents: folder that contains all Intent handlers.
    • interceptors: here you can find all interceptors.
  • models: A folder that contains interaction models for the skill. Each interaction model is defined in a JSON file named according to the locale. For example, es-ES.json.
  • skill.json: The skill manifest. One of the most important files in our project.

Lambda Function in JavaScript

The ASK SDK for Node.js makes it easier for you to build highly engaging skills by allowing you to spend more time implementing features and less time writing boilerplate code.

You can find documentation, samples, and helpful links in their official GitHub repository

The main JavaScript file in our lambda project is index.js, located in lambda/custom folder. This file contains all handlers, interceptors and exports the Skill handler in exports.handler.

The exports.handler function is executed every time AWS Lambda is initiated for this particular function. In theory, an AWS Lambda function is just a single function. This means that we need to define dispatching logic so a single function request can route to appropriate code, hence the handlers.

JavaScript
 




xxxxxxxxxx
1
19


 
1
 /**
2
  * This handler acts as the entry point for your skill, routing all request and response
3
  * payloads to the handlers above. Make sure any new handlers or interceptors you've
4
  * defined are included below. The order matters - they're processed top to bottom 
5
  * */
6
  exports.handler = Alexa.SkillBuilders.custom()
7
      .addRequestHandlers(
8
          LaunchRequestHandler,
9
          HelloWorldIntentHandler,
10
          HelpIntentHandler,
11
          CancelAndStopIntentHandler,
12
          FallbackIntentHandler,
13
          SessionEndedRequestHandler,
14
          IntentReflectorHandler)
15
      .addErrorHandlers(
16
          ErrorHandler)
17
      .addRequestInterceptors(
18
          LocalisationRequestInterceptor)
19
      .lambda();



It is important to take a look into the LaunchRequestHandler as an example of Alexa Skill handler written in Node.js:

JavaScript
 




xxxxxxxxxx
1
15


 
1
  const LaunchRequestHandler = {
2
      //Method that returns true if this handler can execute the current request
3
      canHandle(handlerInput) {
4
          return Alexa.getRequestType(handlerInput.requestEnvelope) === 'LaunchRequest';
5
      },
6
      //Method that will process the request if the method above returns true
7
      handle(handlerInput) {
8
          const speakOutput = handlerInput.t('WELCOME_MSG');
9

          
10
          return handlerInput.responseBuilder
11
              .speak(speakOutput)
12
              .reprompt(speakOutput)
13
              .getResponse();
14
      }
15
  };



Building the Skill With Visual Studio Code

Inside package.json, we will almost always find metadata specific to the project. This metadata helps identify the project and acts as a baseline for users and contributors to get information about the project.

Here is how this file looks:

JSON
 




xxxxxxxxxx
1
21


 
1
  {
2
    "name": "alexa-nodejs-lambda-helloworld",
3
    "version": "1.0.0",
4
    "description": "Alexa HelloWorld example with NodeJS",
5
    "main": "index.js",
6
    "scripts": {
7
      "test": "echo \"Error: no test specified\" && exit 1"
8
    },
9
    "repository": {
10
      "type": "git",
11
      "url": "https://github.com/xavidop/alexa-nodejs-lambda-helloworld.git"
12
    },
13
    "author": "Xavier Portilla Edo",
14
    "license": "Apache-2.0",
15
    "dependencies": {
16
      "ask-sdk-core": "^2.7.0",
17
      "ask-sdk-model": "^1.19.0",
18
      "aws-sdk": "^2.326.0",
19
      "i18next": "^15.0.5"
20
    }
21
  }



With JavaScript or Node.js, the build is a little bit different. For building our Skill, we can run the following command:

JavaScript
 




xxxxxxxxxx
1


 
1
npm install



This command installs a package, and any packages that it depends on. If the package has a package-lock or shrink-wrap file, the installation of dependencies will be driven by that.

It could be the way to build our Alexa Skill.

Running the Skill With Visual Studio Code

The launch.json file in .vscode folder has the configuration for Visual Studio Code, which allow us to run our lambda locally:

JSON
 




xxxxxxxxxx
1
20


 
1
  {
2
    "version": "0.2.0",
3
    "configurations": [
4
        {
5
            "type": "node",
6
            "request": "launch",
7
            "name": "Launch Skill",
8
            // Specify path to the downloaded local adapter(for Node.js) file
9
            "program": "${workspaceRoot}/lambda/custom/local-debugger.js",
10
            "args": [
11
                // port number on your local host where the alexa requests will be routed to
12
                "--portNumber", "3001",
13
                // name of your Node.js main skill file
14
                "--skillEntryFile", "${workspaceRoot}/lambda/custom/index.js",
15
                // name of your lambda handler
16
                "--lambdaHandler", "handler"
17
            ]
18
        }
19
    ]
20
}



This configuration file will execute the following command:

Shell
 




xxxxxxxxxx
1


 
1
node --inspect-brk=28448 lambda\custom\local-debugger.js --portNumber 3001 --skillEntryFile lambda/custom/index.js --lambdaHandler handler



This configuration uses the local-debugger.js file runs a TCP server listening on http://localhost:3001

For a new, incoming Skill request, a new socket connection is established. From the data received on the socket, the request body is extracted, parsed into JSON, and passed to the Skill invoker's lambda handler. The response from the lambda handler is parsed as an HTTP 200 message format as specified here. The response is written onto the socket connection and returned.

After configuring our launch.json file and understanding how the local debugger works, it is time to click on the play button:

Running initial Skill

After executing it, you can send an Alexa POST requests to http://localhost:3001.

Debugging the Skill With Visual Studio Code

Following the steps before, now, you can set up breakpoints wherever you want inside all JS files in order to debug your Skill:

Debugging Skill

Testing Requests Locally

I'm sure you already know the famous tool call Postman. REST APIs have become the new standard in providing a public and secure interface for your service. Though REST has become ubiquitous, it's not always easy to test. Postman makes it easier to test and manage HTTP REST APIs. Postman gives us multiple features to import, test, and share APIs, which will help you and your team be more productive in the long run.

After running your application, you will have an endpoint available at http://localhost:3001. With Postman, you can emulate any Alexa Request.

For example, you can test a LaunchRequest:

JSON
 




xxxxxxxxxx
1
38


 
1
  {
2
    "version": "1.0",
3
    "session": {
4
      "new": true,
5
      "sessionId": "amzn1.echo-api.session.[unique-value-here]",
6
      "application": {
7
        "applicationId": "amzn1.ask.skill.[unique-value-here]"
8
      },
9
      "user": {
10
        "userId": "amzn1.ask.account.[unique-value-here]"
11
      },
12
      "attributes": {}
13
    },
14
    "context": {
15
      "AudioPlayer": {
16
        "playerActivity": "IDLE"
17
      },
18
      "System": {
19
        "application": {
20
          "applicationId": "amzn1.ask.skill.[unique-value-here]"
21
        },
22
        "user": {
23
          "userId": "amzn1.ask.account.[unique-value-here]"
24
        },
25
        "device": {
26
          "supportedInterfaces": {
27
            "AudioPlayer": {}
28
          }
29
        }
30
      }
31
    },
32
    "request": {
33
      "type": "LaunchRequest",
34
      "requestId": "amzn1.echo-api.request.[unique-value-here]",
35
      "timestamp": "2020-03-22T17:24:44Z",
36
      "locale": "en-US"
37
    }
38
  }



Deploying Your Alexa Skill

With the code ready to go, we need to deploy it on AWS Lambda so it can be connected to Alexa.

Before deploy the Alexa Skill, we can show the config file in .ask folder it is empty:

JSON
 




xxxxxxxxxx
1


 
1
    {
2
      "deploy_settings": {
3
        "default": {
4
          "skill_id": "",
5
          "was_cloned": false,
6
          "merge": {}
7
        }
8
      }
9
    }



Deploy Alexa Skill with ASK CLI:

Shell
 




xxxxxxxxxx
1


 
1
ask deploy



As the official documentation says:

When the local Skill project has never been deployed, ASK CLI creates a new Skill in the development stage for your account and then deploys the Skill project. If applicable, ASK CLI creates one or more new AWS Lambda functions in your AWS account and uploads the Lambda function code. Specifically, ASK CLI does the following:

  1. Looks in your Skill project's config file (in the .ask folder, which is in the skill project folder) for an existing Skill ID. If the config file does not contain a Skill ID, ASK CLI creates a new Skill using the skill manifest in the skill project's skill.json file and then adds the skill ID to the skill project's config file.
  2. Look in your Skill project's manifest (skill.json file) for the skill's published locales. These are listed in the manifest.publishingInformation.locales object. For each locale, ASK CLI looks in the Skill project's models folder for a corresponding model file (for example, es-ES.json), then uploads the model to your skill. ASK CLI waits for the uploaded models to build, then adds each model's eTag to the skill project's config file.
  3. Looks in your Skill project's manifest (skill.json file) for AWS Lambda endpoints. These are listed in the manifest.apis..endpoint or manifest.apis..regions..endpoint objects (for example, manifest.apis.custom.endpoint or manifest.apis.smartHome.regions.NA.endpoint). Each endpoint object contains a sourceDir value, and optionally, a URI value. ASK CLI uploads the contents of the sourceDir folder to the corresponding AWS Lambda function and names the Lambda function the same as the URI value. For more details about how ASK CLI performs uploads to Lambda, see AWS Lambda deployment details.
  4. Looks in your Skill project folder for in-skill products, and if it finds any, uploads them to your skill. For more information about in-skill products, see the In-Skill Purchasing Overview.

After the execution of the above command, we will have the config file properly filled:

JSON
 




xxxxxxxxxx
1
33


 
1
  {
2
    "deploy_settings": {
3
      "default": {
4
        "skill_id": "amzn1.ask.skill.ed038d5e-61eb-4383-a480-04e3398b398d",
5
        "was_cloned": false,
6
        "merge": {},
7
        "resources": {
8
          "manifest": {
9
            "eTag": "faa883c92faf9a495407f0d03d5e3790"
10
          },
11
          "interactionModel": {
12
            "es-ES": {
13
              "eTag": "c9e7fd862be0dd3b21252b8bca53c7f7"
14
            }
15
          },
16
          "lambda": [
17
            {
18
              "alexaUsage": [
19
                "custom/default"
20
              ],
21
              "arn": "arn:aws:lambda:us-east-1:141568529918:function:ask-custom-alexa-nodejs-lambda-helloworld-default",
22
              "awsRegion": "us-east-1",
23
              "codeUri": "lambda/custom",
24
              "functionName": "ask-custom-alexa-nodejs-lambda-helloworld-default",
25
              "handler": "index.handler",
26
              "revisionId": "ef2707ee-a366-484d-a4b7-3826a44692dd",
27
              "runtime": "nodejs10.x"
28
            }
29
          ]
30
        }
31
      }
32
    }
33
  }



Test Requests Directly From Alexa

ngrok is a very cool, lightweight tool that creates a secure tunnel on your local machine along with a public URL you can use for browsing your local site or APIs.

When ngrok is running, it listens on the same port that your local web server is running on and proxies external requests to your local machine

From there, it’s a simple step to get it to listen to your web server. Say you’re running your local web server on port 3001. In your terminal, you’d type in: ngrok http 3001. This starts ngrok listening on port 3001 and creates the secure tunnel:

So now, you have to go to Alexa Developer console, go to your skill > endpoints > https, add the HTTPS URL generated above. Eg: https://20dac120.ngrok.io.

Select the My development endpoint as a sub-domain.... option from the dropdown and click the save endpoint at the top of the page.

Go to the Test tab in the Alexa Developer Console and launch your skill.

The Alexa Developer Console will send an HTTPS request to the ngrok endpoint (https://20dac120.ngrok.io), which will route it to your skill running on Web API server at http://localhost:3001.

Resources

  • Official Alexa Skills Kit Node.js SDK - The Official Node.js SDK Documentation
  • Official Alexa Skills Kit Documentation - Official Alexa Skills Kit Documentation

Conclusion

This was a basic tutorial to learn Alexa Skills using Node.js. As you have seen in this example, the Alexa Skill Kit for Node.js and the Alexa Tools like ASK CLI can help us a lot, and also they give us the possibility to create skills in an easy way. I hope this example project is useful to you.

You can find the code in my Github.

I hope it will be useful! If you have any doubts or questions, do not hesitate to contact me or put a comment below!

That's all folks!

Happy coding!

Node.js Command-line interface AWS Lambda AWS code style Visual Studio Code Requests Command (computing)

Opinions expressed by DZone contributors are their own.

Related

  • Alexa Skill With TypeScript
  • Alexa Skill With Python
  • Alexa Skill With Local DynamoDB
  • The Future of Rollouts: From Big Bang to Smart and Secure Approach to Web Application Deployments

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!