Deploying a Nextjs app to AWS
Now let’s let everyone know about our app - we need to go to production.
Let’s save everything we have with git. We want just 1 repository for the whole app. We need to remove the .git folder in our frontend that was created by create-next-app.
rm -rf .git
SST does not initialize a new git repository so we’ll create one
git init
Let’s save to a remote repository. I won’t go into the minutiae. If you aren’t familiar, check out the GitHub docs.
Let’s see if everything builds
npm run build
We can see our next.js app got built, and the whole SST app was built. Let’s deploy to dev.
Before we deploy let’s add to MyStack.ts
stack.addOutputs({
siteUrl: site.url
})
This will print out our Next.js URL in the console.
npm run deploy
Success
Now if we visit that siteUrl - it should look like our site did on localhost.
Going prod
I found myself an unregistered .com domain and registered it with AWS Route 53.
If you want a custom domain, purchase one on Route 53, here’s a guide
Or if you already have a domain not on Route 53
Or if you don’t want a domain, skip this step.
Create a new file .env
DOMAIN_NAME=dropintalk.com
DOMAIN_ALIAS=www.dropintalk.com
Now in MyStack.ts we add the customDomain
property to site
const site = new NextjsSite(stack, "NextSite", {
path: "frontend",
environment: {
NEXT_PUBLIC_API_URL: api.url,
NEXT_PUBLIC_APIGATEWAY_NAME: api.httpApiId,
NEXT_PUBLIC_COGNITO_USER_POOL_ID: auth.userPoolId,
NEXT_PUBLIC_COGNITO_APP_CLIENT_ID: auth.userPoolClientId,
NEXT_PUBLIC_IDENTITY_POOL_ID: auth.cognitoIdentityPoolId ?? "",
NEXT_PUBLIC_REGION: stack.region,
},
customDomain: stack.stage === "prod" ? {
domainName: process.env.DOMAIN_NAME ?? "",
domainAlias: process.env.DOMAIN_ALIAS
} : undefined
})
In this case I only want to assign a domain name if in production. If I deploy to dev, it will use the AWS cloudfront address.
Now to deploy to production
npm run deploy -- --stage prod