How to add a custom domain to a serverless API
In this example we will look at how to add a custom domain to a serverless API using Serverless Stack (SST).
Requirements
- Node.js >= 10.15.1
- We’ll be using Node.js (or ES) in this example but you can also use TypeScript
- An AWS account with the AWS CLI configured locally
- A domain configured using Route 53.
Create an SST app
Let’s start by creating an SST app.
$ npx create-serverless-stack@latest rest-api-custom-domain
$ cd rest-api-custom-domain
By default our app will be deployed to an environment (or stage) called dev
and the us-east-1
AWS region. This can be changed in the sst.json
in your project root.
{
"name": "rest-api-custom-domain",
"stage": "dev",
"region": "us-east-1"
}
Project layout
An SST app is made up of two parts.
-
stacks/
— App InfrastructureThe code that describes the infrastructure of your serverless app is placed in the
stacks/
directory of your project. SST uses AWS CDK, to create the infrastructure. -
src/
— App CodeThe code that’s run when your API is invoked is placed in the
src/
directory of your project.
Setting up an API
Let’s start by setting up an API
Replace the stacks/MyStack.js
with the following.
import * as sst from "@serverless-stack/resources";
export default class MyStack extends sst.Stack {
constructor(scope, id, props) {
super(scope, id, props);
const stage = this.node.root.stage;
// Create the HTTP API
const api = new sst.Api(this, "Api", {
customDomain: `${stage}.example.com`,
routes: {
"GET /": "src/lambda.main",
},
});
// Show the API endpoint in output
this.addOutputs({
ApiEndpoint: api.url,
});
}
}
We are creating an API here using the sst.Api
construct. And we are adding a route to it.
GET /
We are also configuring a custom domain for the API endpoint.
customDomain: `${stage}.example.com`
Our custom domain is based on the stage we are deploying to. So for dev
it’ll be dev.example.com
. To do this, we are accessing the properties of the app from the stack.
Custom domains in Route 53
If you are looking to create a new domain, you can follow this guide to purchase one from Route 53.
Or if you have a domain hosted on another provider, read this to migrate it to Route 53.
If you already have a domain in Route 53, SST will look for a hosted zone with the name set to the base domain. So for example, if your custom domain is set to dev.example.com
, SST will look for a hosted zone called example.com
. If you have it set under a different hosted zone, you’ll need to set that explicitly.
const api = new sst.Api(this, "Api", {
customDomain: {
domainName: "dev.api.example.com",
hostedZone: "example.com",
},
...
});
Adding function code
For this example, we are going to focus on the custom domain. So we are going to keep our Lambda function simple. Refer to the CRUD example, if you want to connect your API to a database.
Replace the src/lambda.js
with the following.
export async function main() {
const response = {
userId: 1,
id: 1,
title: "delectus aut autem",
completed: false
};
return {
statusCode: 200,
body: JSON.stringify(response),
};
}
Note that this function need to be async
to be invoked by AWS Lambda. Even though, in this case we are doing everything synchronously.
Now let’s test our new API.
Starting your dev environment
SST features a Live Lambda Development environment that allows you to work on your serverless apps live.
$ npx sst start
The first time you run this command it’ll take a couple of minutes to do the following:
- It’ll bootstrap your AWS environment to use CDK.
- Deploy a debug stack to power the Live Lambda Development environment.
- Deploy your app, but replace the functions in the
src/
directory with ones that connect to your local client. - Start up a local client.
Deploying your app in this case also means configuring the custom domain. So if you are doing it the first time, it’ll take longer to set that up.
Once complete, you should see something like this.
===============
Deploying app
===============
Preparing your SST app
Transpiling source
Linting source
Deploying stacks
dev-rest-api-custom-domain-my-stack: deploying...
✅ dev-rest-api-custom-domain-my-stack
Stack dev-rest-api-custom-domain-my-stack
Status: deployed
Outputs:
ApiEndpoint: https://9bdtsrrlu1.execute-api.us-east-1.amazonaws.com
The ApiEndpoint
is the API we just created. Head over to the following in your browser. Make sure to replace the URL with your API.
https://9bdtsrrlu1.execute-api.us-east-1.amazonaws.com
You should see a JSON string printed in the browser.
Now try hitting our custom domain.
https://dev.example.com
You should see the same response again. If the page does not load, don’t worry. It can take up to 40 minutes for your custom domain to propagate through DNS. Try again after some time.
Making changes
Let’s make a quick change to our API. It would be good if the JSON strings are pretty printed to make them more readable.
Replace src/lambda.js
with the following.
export async function main() {
const response = {
userId: 1,
id: 1,
title: "delectus aut autem",
completed: false
};
return {
statusCode: 200,
body: JSON.stringify(response, null, " "),
};
}
Here we are just adding some spaces to pretty print the JSON.
If you head back to the custom domain endpoint.
https://dev.example.com
You should see the object in a more readable format.
Deploying your API
Now that our API is tested and ready to go. Let’s go ahead and deploy it for our users. You’ll recall that we were using a dev
environment, the one specified in your sst.json
.
However, we are going to deploy your API again. But to a different environment, called prod
. This allows us to separate our environments, so when we are working in dev
, it doesn’t break the API for our users.
Run the following in your terminal.
$ npx sst deploy --stage prod
Once deployed, you should be able to access that endpoint on the prod custom domain.
https://prod.example.com
A note on these environments. SST is simply deploying the same app twice using two different stage
names. It prefixes the resources with the stage names to ensure that they don’t thrash.
Cleaning up
Finally, you can remove the resources created in this example using the following command.
$ npx sst remove
And to remove the prod environment.
$ npx sst remove --stage prod
This will remove the custom domain mappings as well.
Conclusion
And that’s it! You’ve got a brand new serverless API with a custom domain. A local development environment, to test and make changes. And it’s deployed to production with a custom domain as well. So you can share it with your users. Check out the repo below for the code we used in this example. And leave a comment if you have any questions!
Example repo for reference
github.com/serverless-stack/serverless-stack/tree/master/examples/rest-api-custom-domainFor help and discussion
Comments on this exampleMore Examples
APIs
-
REST API
Building a simple REST API.
-
WebSocket API
Building a simple WebSocket API.
-
TypeScript REST API
Building a REST API with TypeScript.
-
Go REST API
Building a REST API with Golang.
Web Apps
Mobile Apps
GraphQL
Databases
-
DynamoDB
Using DynamoDB in a serverless API.
-
MongoDB Atlas
Using MongoDB Atlas in a serverless API.
-
PostgreSQL
Using PostgreSQL and Aurora in a serverless API.
-
CRUD DynamoDB
Building a CRUD API with DynamoDB.
Authentication
Using AWS IAM
-
Cognito IAM
Authenticating with Cognito User Pool and Identity Pool.
-
Facebook Auth
Authenticating a serverless API with Facebook.
-
Google Auth
Authenticating a serverless API with Google.
-
Twitter Auth
Authenticating a serverless API with Twitter.
-
Auth0 IAM
Authenticating a serverless API with Auth0.
Using JWT
-
Cognito JWT
Adding JWT authentication with Cognito.
-
Auth0 JWT
Adding JWT authentication with Auth0.
Async Tasks
-
Cron
A simple serverless Cron job.
-
Queues
A simple queue system with SQS.
-
Pub/Sub
A simple pub/sub system with SNS.
-
Resize Images
Automatically resize images uploaded to S3.
Editors
-
Debug With VS Code
Using VS Code to debug serverless apps.
-
Debug With WebStorm
Using WebStorm to debug serverless apps.
-
Debug With IntelliJ
Using IntelliJ IDEA to debug serverless apps.
Monitoring
Miscellaneous
-
Lambda Layers
Using the chrome-aws-lambda layer to take screenshots.
-
Middy Validator
Use Middy to validate API request and responses.