I'm grateful for the amazing libraries the community creates, but I feel comfortable relying on few.
Usually, when the time comes to configure DNS on your Serverless project, serverless-domain-manager for managing custom domains and serverless-certificate-creator for ACM will inevitably pop up on your search results.
But as time passes, the last publish date gets older, and weekly downloads start dropping on npm you might beging consider another solution.
Using the CloudFormation templates, supported by Serverless AWS Provider, yu can easily create everything you need for managing your API Gateway DNS configuration, using the resources configuration.
It assumes you're using a serverless.ts configuration file instead of serverless.yml, which I prefer.
const HostedZoneDomainName = "mrjp.xyz"
const DomainName = `api.${HostedZoneDomainName}`
const stage = "${sls:stage}"
const resources = {
Resources: {
ApiGatewayDomainName: {
Type: "AWS::ApiGateway::DomainName",
Properties: {
CertificateArn: { Ref: "Certificate" },
DomainName,
EndpointConfiguration: {
Types: ["EDGE"],
},
},
},
HostedZone: {
Type: "AWS::Route53::HostedZone",
Properties: {
Name: HostedZoneDomainName,
},
},
Certificate: {
Type: "AWS::CertificateManager::Certificate",
Properties: {
DomainName,
ValidationMethod: "DNS",
DomainValidationOptions: [
{
DomainName,
// ValidationDomain: DomainName,
HostedZoneId: { Ref: "HostedZone" },
},
],
},
},
ApiGatewayBasePathMapping: {
Type: "AWS::ApiGateway::BasePathMapping",
Properties: {
DomainName: { Ref: "ApiGatewayDomainName" },
RestApiId: { Ref: "ApiGatewayRestApi" },
Stage: stage,
},
},
ApiGatewayRecordSetGroup: {
Type: "AWS::Route53::RecordSetGroup",
Properties: {
HostedZoneId: { Ref: "HostedZone" },
RecordSets: [
{
Name: DomainName,
Type: "A",
AliasTarget: {
DNSName: {
"Fn::GetAtt": [
"ApiGatewayDomainName",
"DistributionDomainName",
],
},
HostedZoneId: {
"Fn::GetAtt": [
"ApiGatewayDomainName",
"DistributionHostedZoneId",
],
},
EvaluateTargetHealth: false,
},
},
],
},
},
},
Outputs: {
ApiGatewayDomainName: {
Description: "API Gateway Distribution Name",
Value: {
"Fn::GetAtt": ["ApiGatewayDomainName", "DistributionDomainName"],
},
Export: {
Name: "ApiGatewayDomainName",
},
}
},
}If you are using another DNS provider istead of Route53 you can just omit the HostedZone, ApiGatewayRecordSetGroup and Certificate.Properties.DomainValidationOptions.HostedZoneId.
Instead add a Certificate.Properties.ValidationDomain and point it to your prefered domain.
To validate the ACM Cerficate and point to the Cloudront distriuction endpoint, create CNAME records using the output values of the CloudFormation stack with your preferred DNS provider. The DNS record for validating the Certificate will be available in the AWS Console's Certificate Manager or in the CloudFormation stack events.