DEV Community

Jorge Sisco
Jorge Sisco

Posted on

Simplifying Serverless: Custom Domains with AWS SAM

When deploying a Serverless Application Model (SAM) with events that trigger functions via a serverless API gateway, using the default API URL provided by Amazon might not be ideal for your clients.

Example of Default Invoke Base URL:

https://afjdkwosp3.execute-api.eu-central-1.amazonaws.com/dev
Enter fullscreen mode Exit fullscreen mode

Adding a custom domain enhances the appearance of your service, making it more user-friendly.

Setting the Custom Domain in Your SAM template.yaml

Your yaml file for the API will look like this:

MyApi:
  Type: AWS::Serverless::Api
  Properties:
    StageName: !Ref Environment
    DefinitionBody:
      Fn::Transform:
        Name: AWS::Include
        Parameters:
          Location: api/swagger-integrated.yaml
    Domain:
      DomainName: !Sub ${APISubDomainName}.${DomainName}.com
      CertificateArn: !Sub arn:aws:acm:${AWS::Region}:${AWS::AccountId}:certificate/${ACMIDENTIFIER}
      SecurityPolicy: TLS_1_2
      BasePath: '' # Base path replaces stage name; if it's '', you don't have to add the stage name in the endpoints.
Enter fullscreen mode Exit fullscreen mode

To incorporate dynamic values in your template, define DomainName, APISubDomainName, and ACMIDENTIFIER in the parameters section as follows:

Parameters:
  DomainName:
    Type: String
    Default: <your-domain>
  APISubDomainName:
    Type: String
    Default: api
  ACMIDENTIFIER:
    Type: String
    Default: e242ea60-359f-4c49-b052-b9ce6d533cd4
Enter fullscreen mode Exit fullscreen mode

Alternatively, you can avoid hardcoding by omitting the Default values for parameters and add them through the samconfig.toml file. However, our focus here is on establishing a custom domain name for the API.

AWS Certificate Manager

Before deploying our SAM, we must complete a few preparatory steps:

Import your domain SSL certificate to ACM

This process will provide you with your ACMIDENTIFIER, which you can then include in your template.yaml.

Note: It's also necessary to provide the certificate chain to ensure successful SSL certificate verification for requests. Failing to do so might require disabling verification to achieve successful API requests.

Configure the Domain Name to your Rest API

In your domain registrar's panel, add a new CNAME record in your DNS settings that points to your API Gateway's domain name.

Note: The API Gateway's domain name is different from the Invoke URL. This URL can be found in:

AWS API Gateway Custom domain names

Deploy your SAM

You are now ready for deployment. However, be aware that DNS settings changes may take up to 48 hours to propagate fully. Use a DNS checker to confirm the CNAME's propagation and to ensure the configuration is correct. Once verified, your API will be accessible via the custom domain.

Top comments (0)