Generating TLS certificates for external domains in SST

You know how sometimes, you can spend hours and hours debugging something, only to discover the fix is a few lines of code? That's what creating certificates in sst.dev was like. I kept forgetting that SST wraps AWS Cloud Development Kit (CDK), and that any construct not available in SST could be grabbed from the underlying CDK. Oops. Score one for "I should've read the docs more thoroughly and slowly".

Anyways, here's the entire SST config you'd need to add a custom certificate to your site stack in SST:

import { Certificate, CertificateValidation } from 'aws-cdk-lib/aws-certificatemanager';
import type { SSTConfig } from 'sst';
import { Config, SvelteKitSite } from 'sst/constructs';

export default {
    config(_input) {
        return {
            name: 'your-site',
            region: 'us-east-1',
        };
    },
    stacks(app) {
        app.stack(function Site({ stack }) {
            const certificate = new Certificate(this, 'Certificate', {
                domainName: '*.yourdomain.com',
                subjectAlternativeNames: ['yourdomain.com'],
                // Can also do `fromEmail`, but DNS is more maintainable if you
                // have control of the DNS records.
                validation: CertificateValidation.fromDns(),
            });
            if (stack.stage !== 'prod') {
                // Don't need to keep dev certs around forever.
                certificate.applyRemovalPolicy(RemovalPolicy.DESTROY);
            }

            const site = new SvelteKitSite(stack, 'site', { // or whatever site stack you want to use
                customDomain: {
                    // Note that we're supplying the root domain, not the subdomain wildcard.
                    domainName: 'yourdomain.com',
                    isExternalDomain: true,
                    cdk: {
                        certificate,
                    },
                },
            });

            stack.addOutputs({
                url: site.url,
            });
        });
    },
} satisfies SSTConfig;

Voila! SST is actually pretty cool. Knowing just a bit about AWS Lambda has unlocked a lot of ideas for me.

Did you find this article valuable?

Support Marty's Random Thoughts by becoming a sponsor. Any amount is appreciated!