Custom Domains in serverless APIs
In the previous chapter we purchased a new domain on Route 53. Now let’s use it for our serverless API.
In your stacks/ApiStack.ts
replace the function declaration with the following to add app
from StackContext
.
export function ApiStack({ stack, app }: StackContext) {
Then, add the following above the defaults: {
line in stacks/ApiStack.ts
.
customDomain: app.stage === "prod" ? "<Your Domain>" : undefined,
This tells SST that we want to use a custom domain if we are deploying to the prod
stage. We are not setting one for our dev
stage, or any other stage.
We could for example, base it on the stage name, api-${app.stage}.my-serverless-app.com
. So for dev
it might be api-dev.my-serverless-app.com
. But we’ll leave that as an exercise for you.
We also need to update the outputs of our API stack.
Finally, replace the stack.addOutputs
call at the bottom of stacks/ApiStack.ts
.
stack.addOutputs({
ApiEndpoint: api.customDomainUrl || api.url,
});
Here we are returning the custom domain URL, if we have one. If not, then we return the auto-generated URL.
Deploy the App
Let’s deploy these changes to prod.
Run the following from your project root.
$ pnpm sst deploy --stage prod
At the end of the deploy process you should see something like this.
✓ Deployed:
StorageStack
ApiStack
ApiEndpoint: https://api.my-serverless-app.com
...
This is great! We now have our app deployed to prod and our API has a custom domain.
Next, let’s use our custom domain for our React app as well.
For help and discussion
Comments on this chapter