Zero Stored Secrets: Deploying Next.js to AWS with SST, OpenNext and GitHub OIDC
A security-first pipeline for Next.js on AWS: GitHub Actions with OIDC, SST and OpenNext on S3, CloudFront and Lambda, environment gates, scoped IAM and safe PR previews.
- Author
- Navinda Chandrasiri
- Published
- Reading time
- 13 min read

On this page
- What actually gets deployed
- The threat model
- Step 1: Add SST to your Next.js app
- Step 2: Create the production deploy role
- Be honest about the permissions
- Step 3: Configure the GitHub Environment
- Step 4: The deployment workflow
- Step 5: Pull-request previews, safely
- Step 6: Runtime secrets without GitHub secrets
- Step 7: Harden the delivery layer
- Supply chain: the part everyone forgets
- When things go wrong
- The final checklist
- Wrapping up
Getting a Next.js app onto AWS is easy. Getting it there in a way you would still be comfortable with after a dependency gets compromised, a teammate leaves, or someone opens a hostile pull request is the part most tutorials skip.
This post builds a deployment pipeline with one rule: no long-lived AWS credentials anywhere. GitHub Actions authenticates to AWS with OIDC, SST provisions the infrastructure, and OpenNext adapts Next.js to run on Lambda, S3 and CloudFront. Along the way we gate production behind a GitHub Environment, scope IAM carefully, handle runtime secrets properly, and make pull-request previews safe.
If you have not set up the GitHub to AWS trust yet, read Goodbye Access Keys: Connecting GitHub Actions to AWS with OIDC first. This post builds on it and does not repeat the identity provider setup.
This post is written against SST v3. SST moves quickly, so treat component options as a starting point and confirm them in the current documentation.
What actually gets deployed#
When you deploy a Next.js app with SST's Nextjs component, OpenNext builds your app and SST creates the AWS resources around it. At a high level you get:
- S3 for static assets and the incremental static regeneration cache.
- A Lambda function that runs your server-rendered routes, API routes and middleware.
- A separate function for image optimisation.
- CloudFront in front of everything, handling TLS, caching and routing between S3 and the functions.
- Supporting pieces such as a queue and a table that power on-demand revalidation.
That is a lot of AWS resources created from one sst deploy, and it tells you something important about security: the identity that runs the deploy has to be allowed to create IAM roles, Lambda functions, buckets and distributions. That is powerful. Most of this post is about containing that power.
The threat model#
Design decisions are easier when you say what you are defending against:
| Threat | Defence in this setup |
|---|---|
| A stolen CI credential works forever | OIDC. Credentials are temporary and there is nothing stored to steal |
| Any branch or fork can deploy to production | Trust policy pinned to a GitHub Environment, which is restricted to main |
| A malicious pull request runs code with cloud access | Previews use a separate, low-privilege role in a sandbox account |
| A compromised CI role does damage across everything | Separate AWS accounts per environment plus a permissions boundary |
| A poisoned third-party action or npm package | Pinned action SHAs, lockfile installs, pinned OpenNext version, Dependabot |
| Runtime secrets leak through the repository or logs | SST secrets stored per stage, never in the workflow or the code |
No single control covers all of them. The point is that each layer limits what the next failure can cost you.
Step 1: Add SST to your Next.js app#
From the root of your Next.js project:
npx sst@latest initSST detects Next.js and creates an sst.config.ts. Replace it with something like this:
/// <reference path="./.sst/platform/config.d.ts" />
export default $config({
app(input) {
return {
name: "my-web",
home: "aws",
// Never delete production resources by accident.
removal: input?.stage === "production" ? "retain" : "remove",
protect: ["production"].includes(input?.stage),
providers: { aws: { region: "ap-southeast-1" } },
};
},
async run() {
const apiKey = new sst.Secret("ApiKey");
const web = new sst.aws.Nextjs("Web", {
link: [apiKey],
// Only production gets the real domain. Other stages use the generated CloudFront URL.
domain: $app.stage === "production" ? "example.com" : undefined,
// Pin the OpenNext version you have tested (see "Supply chain" below):
// openNextVersion: "your-tested-version",
});
return { url: web.url };
},
});Three details are worth pausing on:
removal: "retain"andprotectmean a straysst removeor a bad refactor cannot delete production.- The stage (
production,staging,pr-42) is how SST keeps environments isolated. Everything that follows keys off it. - The domain is set only for production. Preview stages get an automatically generated URL, so a pull request never touches your real DNS.
SST bootstraps each AWS account and region the first time it runs there, creating a state bucket and an assets bucket. That means you do not need a manual first deploy. Your pipeline can do it, provided the deploy role is allowed to.
Step 2: Create the production deploy role#
Use a dedicated AWS account for production, created under AWS Organizations if you have it. This is the single most effective control in the whole post. If CI is ever compromised, the damage is limited to that account, and your development sandbox, billing and identity accounts are untouched.
In the production account, create the GitHub identity provider as described in the previous post, then create a role whose trust policy accepts only the production environment of your repository:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Federated": "arn:aws:iam::111111111111:oidc-provider/token.actions.githubusercontent.com"
},
"Action": "sts:AssumeRoleWithWebIdentity",
"Condition": {
"StringEquals": {
"token.actions.githubusercontent.com:aud": "sts.amazonaws.com",
"token.actions.githubusercontent.com:sub": "repo:my-org/my-web:environment:production"
}
}
}
]
}Notice there is no branch in that subject. The branch restriction lives on the GitHub side, on the environment itself (Step 3), and AWS trusts the environment. A job can only claim environment:production after passing GitHub's protection rules.
Be honest about the permissions#
SST has to create IAM roles, Lambda functions, CloudFront distributions, S3 buckets, queues and tables, and the exact set grows as SST adds features. Writing a minimal policy for that is brittle, and a policy that is too tight turns every SST upgrade into a failed deploy.
Here is the uncomfortable truth: a role that can create IAM roles is effectively an administrator inside its account. You cannot fully avoid that with a deploy tool that provisions infrastructure. So the strategy is containment rather than pretending the role is small:
- Isolate by account. Production lives in its own account (above).
- Attach a permissions boundary that blocks the actions an attacker would reach for first: creating human users and access keys, tampering with audit logging, and touching the organisation.
- Alarm on it. CloudTrail plus an alert on unexpected role assumptions.
A boundary that allows everything except the dangerous actions looks like this:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AllowDeployWork",
"Effect": "Allow",
"Action": "*",
"Resource": "*"
},
{
"Sid": "DenyCredentialAndAuditTampering",
"Effect": "Deny",
"Action": [
"iam:CreateUser",
"iam:CreateAccessKey",
"iam:CreateLoginProfile",
"iam:UpdateLoginProfile",
"iam:DeleteOpenIDConnectProvider",
"cloudtrail:StopLogging",
"cloudtrail:DeleteTrail",
"cloudtrail:UpdateTrail",
"organizations:*",
"account:*"
],
"Resource": "*"
}
]
}Create the role, the boundary and the attachment with the CLI, using admin credentials in the production account:
aws iam create-role \
--role-name github-actions-sst-production \
--assume-role-policy-document file://trust-production.json \
--max-session-duration 3600
aws iam create-policy \
--policy-name ci-deploy-boundary \
--policy-document file://boundary.json
aws iam put-role-permissions-boundary \
--role-name github-actions-sst-production \
--permissions-boundary arn:aws:iam::111111111111:policy/ci-deploy-boundary
aws iam attach-role-policy \
--role-name github-actions-sst-production \
--policy-arn arn:aws:iam::aws:policy/AdministratorAccessThe effective permissions are the intersection of the attached policy and the boundary: everything, minus the deny list. This is a guard rail, not a sandbox. It stops the obvious abuses, and the account boundary is what limits the rest.
If your team can afford to maintain a hand-written least-privilege policy for SST, that is better still. Many teams find the account and boundary approach the right balance between safety and upgrade pain.
Step 3: Configure the GitHub Environment#
In your repository, open Settings, then Environments, and create production:
- Deployment branches and tags: select Selected branches and allow only
main. A job on any other branch cannot even use this environment. - Required reviewers: add yourself or the team lead so that a deployment waits for an explicit approval. Note that for private repositories this feature needs a paid GitHub plan.
- Environment variables: add
AWS_DEPLOY_ROLE_ARNwith the role ARN andAWS_REGIONwith your region. These are not secrets. A role ARN is useless without a token from the right repository.
At this point the trust chain is complete: AWS trusts the production environment, and GitHub only lets approved jobs from main enter it.
Step 4: The deployment workflow#
name: Deploy production
on:
push:
branches: [main]
# Nothing by default. Each job opts in to exactly what it needs.
permissions: {}
# Never run two production deploys at once, and never cancel one halfway.
concurrency:
group: deploy-production
cancel-in-progress: false
jobs:
verify:
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 22
cache: npm
- run: npm ci
- run: npm run lint
- run: npm run typecheck
- run: npm test
deploy:
needs: verify
runs-on: ubuntu-latest
environment: production
permissions:
id-token: write
contents: read
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 22
cache: npm
- run: npm ci
- name: Configure AWS credentials (OIDC)
uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: ${{ vars.AWS_DEPLOY_ROLE_ARN }}
aws-region: ${{ vars.AWS_REGION }}
role-session-name: gha-${{ github.run_id }}
- name: Deploy with SST
run: npx sst deploy --stage productionWhy it is shaped this way:
permissions: {}at the top. Theverifyjob (which runs your tests and third-party code) gets read-only repository access and no ability to request an OIDC token at all. Onlydeploycan talk to AWS.environment: productionis what makes the OIDC subject match the trust policy, and it triggers the approval gate.needs: verifymeans a failing test never reaches AWS.concurrencyavoids two runs fighting over SST's state lock. If a run is killed anyway and leaves a lock behind,npx sst unlock --stage productionclears it.role-session-nameincludes the run ID, so every action in CloudTrail can be traced back to a specific workflow run.
Step 5: Pull-request previews, safely#
Preview deployments are great and also the riskiest part of the pipeline. A pull request runs code that nobody has reviewed (including npm install scripts) in a job that can talk to AWS. So previews get their own, much weaker setup:
- A separate sandbox AWS account, with a budget alarm.
- A separate role whose trust policy accepts only the pull-request subject:
repo:my-org/my-web:pull_request. - No access to production secrets. Preview stages use their own test values.
- No forks. GitHub does not issue OIDC tokens to fork workflows anyway, and you should not want them to.
name: Preview
on:
pull_request:
types: [opened, synchronize, reopened]
permissions: {}
concurrency:
group: preview-${{ github.event.number }}
cancel-in-progress: true
jobs:
preview:
if: github.event.pull_request.head.repo.full_name == github.repository
runs-on: ubuntu-latest
permissions:
id-token: write
contents: read
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 22
cache: npm
- run: npm ci
- uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: ${{ vars.AWS_PREVIEW_ROLE_ARN }}
aws-region: ${{ vars.AWS_REGION }}
role-session-name: gha-preview-${{ github.event.number }}
- run: npx sst deploy --stage pr-${{ github.event.number }}Because every preview is its own stage (pr-42), it is an isolated copy with its own URL, and because the stage is not production, the config above sets removal: "remove" so it can be fully deleted. Clean up when the pull request closes:
name: Remove preview
on:
pull_request:
types: [closed]
permissions: {}
jobs:
remove:
if: github.event.pull_request.head.repo.full_name == github.repository
runs-on: ubuntu-latest
permissions:
id-token: write
contents: read
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 22
cache: npm
- run: npm ci
- uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: ${{ vars.AWS_PREVIEW_ROLE_ARN }}
aws-region: ${{ vars.AWS_REGION }}
- run: npx sst remove --stage pr-${{ github.event.number }}If you want to review changes without deploying, npx sst diff --stage production shows what a deploy would change. That is a good fit for a read-only role.
Step 6: Runtime secrets without GitHub secrets#
Your app probably needs API keys, database URLs or webhook secrets at runtime. Do not put them in repository secrets and pass them through the workflow. They would sit in the GitHub UI, in every job's environment, and potentially in build output.
SST has a better model. Declare the secret in the config (as ApiKey above), then set it per stage from your machine using credentials for that account:
npx sst secret set ApiKey "the-production-value" --stage production
npx sst secret set ApiKey "a-harmless-test-value" --stage stagingLink it to the Next.js app (already done with link: [apiKey]) and read it in server code:
import { Resource } from "sst";
export async function GET() {
const key = Resource.ApiKey.value;
// use key on the server only
return Response.json({ ok: true });
}The value lives per stage in your AWS account, and the repository and workflow never contain it. Set secrets before the first deploy of a stage, because a missing value fails the deploy.
One reminder about Next.js itself: anything prefixed with NEXT_PUBLIC_ is baked into the browser bundle at build time. Never put a secret in one.
Step 7: Harden the delivery layer#
Once the pipeline is safe, look at what it ships.
Check the bucket. SST keeps the assets bucket private behind CloudFront. Confirm that in the S3 console: Block Public Access should be on for all four settings, and there should be no public bucket policy. This takes thirty seconds and is worth doing once per account.
Add security headers. Set them in next.config.ts:
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
async headers() {
return [
{
source: "/(.*)",
headers: [
{ key: "Strict-Transport-Security", value: "max-age=63072000; includeSubDomains; preload" },
{ key: "X-Content-Type-Options", value: "nosniff" },
{ key: "Referrer-Policy", value: "strict-origin-when-cross-origin" },
{ key: "X-Frame-Options", value: "DENY" },
],
},
];
},
};
export default nextConfig;Then verify with curl -I https://your-domain.com. In this architecture, headers from next.config are applied by the server function. Files that CloudFront fetches straight from S3 (such as /_next/static and your public folder) may not carry them. If you need the headers on every response, attach a CloudFront response headers policy to the distribution. The exact transform hook for doing that depends on your SST version, so follow the SST documentation for it rather than copying a snippet from a blog post, including this one.
Consider a WAF. AWS WAF in front of CloudFront gives you rate limiting and managed rule sets. It costs money, so switch it on for public production sites rather than for every preview.
Turn on the boring safety nets. CloudTrail in every account, an AWS Budgets alarm in every account, and an alert when a role is assumed from somewhere unexpected.
Supply chain: the part everyone forgets#
Your pipeline now has no stored credentials, but it still runs other people's code. A few cheap habits help:
- Install from the lockfile with
npm ci, nevernpm install, in CI. - Pin actions to a full commit SHA for anything that touches AWS or secrets, with the version in a comment:
uses: aws-actions/configure-aws-credentials@full-commit-sha # v4. Moving tags can be re-pointed. Commit hashes cannot. - Pin OpenNext with the
openNextVersionoption of theNextjscomponent, so a new upstream release cannot change your build between two deploys without you choosing it. - Let Dependabot propose updates rather than updating blindly.
# .github/dependabot.yml
version: 2
updates:
- package-ecosystem: github-actions
directory: /
schedule:
interval: weekly
- package-ecosystem: npm
directory: /
schedule:
interval: weeklyWhen things go wrong#
Not authorized to perform sts:AssumeRoleWithWebIdentity. The subject did not match. For production the job must declareenvironment: production, and the trust policy must sayenvironment:production. See the troubleshooting table in the OIDC post.AccessDeniedduring the first deploy. SST is bootstrapping and your boundary or role is missing something. Read the denied action in the error and decide whether it belongs in the role.- The state lock is held. A previous run was cancelled mid-deploy. Run
npx sst unlock --stage productiononce you are sure no deploy is active. - Environment variables look empty in the job. Variables defined on an environment are only available to jobs that declare that environment.
- Preview deploys fail for pull requests from forks. That is by design. GitHub does not issue OIDC tokens to fork workflows.
The final checklist#
Before you call it done, you should be able to answer yes to all of these:
- There are no AWS access keys in GitHub secrets, in the repository or in any
.envfile in CI. - The production role trusts exactly one subject:
repo:my-org/my-web:environment:production. - The
productionenvironment only acceptsmainand requires approval. - Production runs in its own AWS account, and the CI role has a permissions boundary.
- Previews use a different role in a different account, and fork pull requests are skipped.
- Runtime secrets are SST secrets, set per stage, and absent from workflows.
- Workflows start with
permissions: {}and only deploy jobs can requestid-token: write. - Actions, OpenNext and dependencies are pinned and updated through reviewed pull requests.
- CloudTrail, a budget alarm and security headers are in place.
Wrapping up#
None of these controls is exotic. OIDC removes the credential worth stealing, GitHub Environments decide who may deploy, AWS accounts and boundaries cap the damage, and a handful of habits keep third-party code in check. Together they turn "we deploy from CI" into something you can explain to a security reviewer without crossing your fingers.
Start with OIDC and the environment gate, since those two give you the biggest win, and add the rest as the project grows.
Related reading
From git push to Global CDN: Hosting a Secure Next.js Static Site on S3 and CloudFront with Terraform and CodePipeline
Learn to host a Next.js static export on a private S3 bucket with CloudFront, a custom domain, HTTPS, security headers, and automated GitHub to CodePipeline deployments using Terraform.
AWSTerraformCloudFrontS3
12 min readGoodbye Access Keys: Connecting GitHub Actions to AWS with OIDC
Replace long-lived AWS keys in GitHub secrets with short-lived OIDC credentials. IAM setup, trust policies, a working workflow, Terraform and a troubleshooting guide.
AWSGitHub ActionsOIDCIAM
9 min readZero Servers, One Bucket: Deploying a Next.js Static Site to Amazon S3 with Terraform and CodePipeline
Host a Next.js static export on Amazon S3 website hosting and automate every deployment from GitHub using AWS CodePipeline, CodeBuild, and Terraform, with the trade-offs explained honestly.
AWSTerraformS3CodePipeline
12 min read