Set Custom Domains

Our serverless API uses API Gateway and it gives us some auto-generated endpoints. We would like to configure them to use a scheme like or something similar.

In the first part of the tutorial we had added our domain to Route 53. If you haven't done so you can read more about it here. To automate this we use the serverless-domain-manager / guide. For a production deployment make sure your role has limited rights.

We will use the serverless framework plugins as they go directly to the API instead of using cloud formation as this seems to be complex and not working very well for the domains.

First create the ssl certificate through serverless-certificate-creator and then add the domain.

npm install --save-dev serverless-certificate-creator serverless-domain-manager

Update now your serverless.yaml it might make sense if the certificate and domains are used in multiple projects to create a seperate stack:

- serverless-certificate-creator
- serverless-domain-manager
certificateName: ''
basePath: ''
stage: ${self:provider.stage}
createRoute53Record: true
certificateName: '' //required
idempotencyToken: 'apid10lde' //optional
hostedZoneIds: 'Z3A1XXXXeXXFVX' //required if hostedZoneNames is not set
region: us-east-1 // optional - default is us-east-1 which is required for custom api gateway domains of Type Edge (default)
enabled: true // optional - default is true. For some stages you may not want to use certificates (and custom domains associated with it).
rewriteRecords: false

Now you can run:

serverless create-cert
serverless create_domain

To add more apis to the custome domain you need to add the plugin and the customDomain entry into the serverless.yaml of the service. Then simply deploy your service without running the create_domain command again. If you have multiple stages you might create differrent custome domains e.g. for prod and for dev. for this update the domain name to api-${self:provider.stage}, these domains need to be created once for each stage. As a certificate it makes sense to only create on certificate with a wildcard entry like * or on certificate that has the other stages as an alias.

Serverless Framework will now go through and configure the domain for this API Gateway endpoint, create the SSL certificate and attach it to the domain. This process can take up to 40 mins.

Now that we've automated our deployments, let’s do a quick test to see what will happen if we make a mistake and push some faulty code to production.