Next.js Website



The nextjs-website resource is designed to deploy Next.js applications to AWS. It leverages serverless technologies like AWS Lambda and Lambda@Edge to run your application efficiently. Stacktape automatically provisions and configures all the necessary AWS resources, so you can focus on writing your application code.

resources:
  web:
    type: nextjs-web
    properties:
      appDirectory: ./

Basic use of nextjs-web resource

How it Works

Stacktape uses the open-source project OpenNEXT to build your Next.js application, making it compatible with AWS Lambda. Behind the scenes, Stacktape provisions a set of AWS resources to host your app:

ComponentTypeDescription
Server functionLambda or Lambda@EdgeRuns your Next.js server logic.
Asset BucketS3 bucketStores static assets (like images, CSS) and cached assets.
Image optimization functionLambdaHandles on-the-fly image optimization for the Next.js <Image> component.
CloudFront distributionCDNA CDN that caches and distributes your website content globally for low latency.
Revalidation functionLambdaHandles content revalidation when using Incremental Static Regeneration (ISR).
Revalidation queueSQS QueueA message queue used by the server function to trigger the revalidation function.
Revalidation tableDynamoDB tableA NoSQL database that supports Next.js revalidateTag for on-demand revalidation.
Revalidation inserterLambdaPopulates the revalidation table during deployment.
Warmer function (Optional)LambdaKeeps the server function warm to prevent cold starts (not available for Lambda@Edge).

For more information refer to OpenNext docs.

Architecture overview (credit: OpenNext)

Edge Deployments

To deploy your Next.js application to the edge for lower latency, you can use Lambda@Edge by setting the useEdgeLambda property to true. This deploys your server function to CDN locations around the world.

Trade-offs: Slower deploys, no warmServerInstances, no response streaming.

resources:
  web:
    type: nextjs-web
    properties:
      appDirectory: ./
      useEdgeLambda: true

Performance Optimization

Mitigating Cold Starts

To mitigate cold starts and ensure your server function responds quickly, you can enable a warmer. This keeps a specified number of function instances active. By default, the warmer is disabled. This feature is not available when using useEdgeLambda.

A separate "warmer" function periodically pings the SSR Lambda. Not available with useEdgeLambda: true.

resources:
  web:
    type: nextjs-web
    properties:
      appDirectory: ./
      warmServerInstances: 5

Security

Web Application Firewall

You can protect your Next.js application from common web exploits by attaching a web-app-firewall. This can help prevent attacks that could affect your application's availability, compromise security, or consume excessive resources.

resources:
  web:
    type: nextjs-web
    properties:
      appDirectory: ./
      useFirewall: waf

  waf:
    type: web-app-firewall
    properties:
      scope: cdn

Environment variables

You can inject environment variables into the server function. These variables are available at build time and runtime.

A list of environment variables to pass to the script or command.

Values can be:

resources:
  web:
    type: nextjs-web
    properties:
      appDirectory: ./
      environment:
        - name: STATIC_ENV_VAR
          value: my-env-var
        - name: DYNAMICALLY_SET_ENV_VAR
          value: $MyCustomDirective('input-for-my-directive')
        - name: DB_HOST
          value: $ResourceParam('myDatabase', 'host')
        - name: DB_PASSWORD
          value: $Secret('dbSecret.password')

Custom Domain Names

You can configure custom domains for your Next.js application. Stacktape will automatically provision an SSL certificate and configure DNS routing.

Your domain must be added as a Route53 hosted zone in your AWS account first.

DomainConfigurationAPI referenceParent:NextjsWeb
domainNameRequired

Your domain name (e.g., mydomain.com or api.mydomain.com).

Type: string

Don't include the protocol (https://). The domain must have a Route53 hosted zone in your AWS account, with your registrar's nameservers pointing to it.

Stacktape automatically creates a DNS record and provisions a free TLS certificate.

customCertificateArn

Use your own TLS certificate instead of the auto-generated one.

Type: string

Provide the ARN of an ACM certificate from your AWS account. Only needed if you have specific certificate requirements (e.g., EV/OV certs). By default, Stacktape provisions and renews free certificates automatically.

disableDnsRecordCreation

Skip DNS record creation for this domain.

Type: boolean

Set to true if you manage DNS records yourself (e.g., through Cloudflare or another DNS provider). Stacktape will still provision the TLS certificate but won't touch your DNS.

resources:
  web:
    type: nextjs-web
    properties:
      appDirectory: ./
      customDomains:
        - domainName: mydomain.com

Accessing Other Resources

By default, most AWS resources are not allowed to communicate with each other. This is a security measure to ensure resource isolation. To allow your Next.js application to access other resources, you need to grant permissions explicitly.

  • IAM Permissions: Access to most AWS services is controlled by IAM (Identity and Access Management). Stacktape automatically manages the necessary permissions for the resources it creates.
  • Relational Databases: Relational Databases use their own access control (a connection string with a username and password) and are not managed by IAM. They are accessible by default unless you configure more restrictive access controls.

If your Next.js application needs to communicate with other resources in your stack, you can grant permissions in two ways:

Using connectTo

The connectTo property is a simplified way to grant access to other Stacktape-managed resources. Stacktape will automatically configure the required IAM permissions and inject connection details as environment variables into your function.

resources:
  web:
    type: nextjs-web
    properties:
      appDirectory: ./
      connectTo:
        - myDatabase

  myDatabase:
    type: relational-database
    properties:
      engine:
        type: aurora-postgresql
        properties:
          instances:
            - instanceSize: db.t4g.medium

List the names of resources this workload needs to communicate with. Stacktape automatically:

  • Grants IAM permissions (e.g., S3 read/write, SQS send/receive)
  • Opens network access (security group rules for databases, Redis)
  • Injects environment variables with connection details: STP_[RESOURCE_NAME]_[PARAM]

Example: connectTo: ["myDatabase", "myBucket"] gives this workload full access to both resources and injects STP_MY_DATABASE_CONNECTION_STRING, STP_MY_BUCKET_NAME, etc.

Using iamRoleStatements

For more granular control, you can provide raw IAM role statements. This allows you to define precise permissions for accessing any AWS resource, including those not managed by Stacktape.

resources:
  web:
    type: nextjs-web
    properties:
      appDirectory: ./
      iamRoleStatements:
        - Resource:
            - $CfResourceParam('NotificationTopic', 'Arn')
          Effect: 'Allow'
          Action:
            - 'sns:Publish'

cloudformationResources:
  NotificationTopic:
    Type: AWS::SNS::Topic

Known Issues

Here are some known issues and workarounds when deploying Next.js applications with Stacktape.

Bundle Size

Next.js can sometimes include development dependencies in the production bundle, which significantly increases its size. To prevent this, add the following configuration to your next.config.js file:

// next.config.js
module.exports = {
  outputFileTracingExcludes: {
    '*': [
      '@swc/core',
      'esbuild',
      'uglify-js',
      'watchpack',
      'webassemblyjs',
      'sharp'
    ],
  },
}

Fetch Behavior for ISR

Applies only to Next.js v13.5.1 and later.

A bug in Next.js can cause inconsistent revalidation behavior when using ISR. It may use the lowest revalidate value from all fetch calls on a page, ignoring their individual settings. To fix this, add the following snippet to your root layout component:

// app/layout.tsx
export default function RootLayout({ children }: { children: React.ReactNode }) {
  const asyncStorage = require("next/dist/client/components/static-generation-async-storage.external");
  //@ts-ignore
  const staticStore = (fetch as any).__nextGetStaticStore?.() || asyncStorage.staticGenerationAsyncStorage;
  const store = staticStore.getStore();
  if (store) {
    store.isOnDemandRevalidate = store.isOnDemandRevalidate && !(process.env.OPEN_NEXT_ISR === "true");
  }
  return <>{children}</>;
}

Pricing

All resources provisioned for your Next.js application are pay-per-use. This means you pay nothing for idle resources and only for what you use. As your traffic grows, your costs will increase, but they are generally much lower than managed hosting providers like Vercel.

Cost Breakdown

CloudFront CDN

CloudFront serves as a CDN, caching your content in edge locations close to your users.

  • Data Transfer: ~$0.085 per GB (first 1 TB/month is free)
  • HTTPS Requests: ~$0.0085 per 10,000 requests (first 10,000,000/month are free)

For current pricing, see the AWS CloudFront Pricing page.

AWS Lambda

Costs depend on whether you use regional Lambda or Lambda@Edge.

Regional AWS Lambda
  • Execution Duration: ~$0.0000000167 per millisecond (with 1024MB memory)
  • Requests: $0.20 per 1 million requests
Lambda@Edge
  • Execution Duration: ~$0.00000005001 per millisecond (with 1024MB memory)
  • Requests: $0.60 per 1 million requests

For current pricing, see the AWS Lambda Pricing page.

S3 for Caching

A S3 bucket is used to store the cache for ISR and fetch requests.

  • GetObject: ~$0.0004 per 1,000 requests (reading from cache)
  • PutObject: ~$0.005 per 1,000 requests (writing to cache)

For current pricing, see the AWS S3 Pricing page.

DynamoDB for Cache Tags

A DynamoDB table stores cache tags for on-demand revalidation.

  • Read Requests: ~$0.25 per 1 million read units
  • Write Requests: ~$1.25 per 1 million write units

For current pricing, see the AWS DynamoDB Pricing page.

Example Pricing

The following example is a rough estimate for a website with 300,000 monthly visitors. Actual costs can vary significantly based on your application's caching strategy, dynamic content, and API usage.

Assumptions

  • Monthly Visitors: 300,000
  • Page Views per Visitor: 3
  • Cache Hit Rate: 50% of page views are served from the CDN cache.
  • API Calls per Page: 2 API calls for each page view that hits the server.

This results in:

  • Total Page Views: 900,000
  • Server Page Views: 450,000
  • Total Server Requests: 1,350,000 (450,000 page views + 900,000 API calls)

Monthly Cost Estimate

ServiceCalculationEstimated Cost
CloudFrontWithin free tier limits$0
AWS Lambda675,000 requests, 100ms duration each$1.26
S3 Storage675,000 reads and writes$3.65
DynamoDB675,000 reads and writes$1.01
Total~$5.92 per month

API reference

NextjsWebAPI reference
typeRequired
No description

Type: string "nextjs-web"

properties.appDirectoryRequired

Directory containing your next.config.js. For monorepos, point to the Next.js workspace.

Type: string

properties.serverLambda

Customize the SSR Lambda function (memory, timeout, VPC, logging).

Type: NextjsServerLambdaProperties

properties.warmServerInstances

Number of Lambda instances to keep warm (pre-initialized) to reduce cold starts.

Type: number

A separate "warmer" function periodically pings the SSR Lambda. Not available with useEdgeLambda: true.

properties.useEdgeLambda

Run SSR at CloudFront edge locations for lower latency worldwide.

Type: boolean

Trade-offs: Slower deploys, no warmServerInstances, no response streaming.

properties.buildCommand

Override the default next build command.

Type: string

properties.dev

Dev server config for stacktape dev. Defaults to next dev.

Type: Object

properties.fileOptions

Set custom headers (e.g., Cache-Control) for static files matching a pattern.

Type: Array of DirectoryUploadFilter

properties.environment

Environment variables for the SSR function. Use $ResourceParam() or $Secret() for dynamic values.

Type: Array of EnvironmentVar

properties.customDomains

Attach custom domains with auto-managed DNS records and TLS certificates.

Type: Array of DomainConfiguration

Prerequisite: A Route 53 hosted zone for your domain must exist in your AWS account.

properties.useFirewall

Name of a web-app-firewall resource to protect this app. Firewall scope must be cdn.

Type: string

properties.streamingEnabled

Stream SSR responses for faster Time to First Byte and up to 20 MB response size (vs 6 MB default).

Type: boolean

Not compatible with useEdgeLambda: true.

properties.cdn

CDN cache controls for SSR routes and specific path patterns.

Type: SsrWebCdnConfig

properties.connectTo

Give this resource access to other resources in your stack.

Type: Array of string

List the names of resources this workload needs to communicate with. Stacktape automatically:

  • Grants IAM permissions (e.g., S3 read/write, SQS send/receive)
  • Opens network access (security group rules for databases, Redis)
  • Injects environment variables with connection details: STP_[RESOURCE_NAME]_[PARAM]

Example: connectTo: ["myDatabase", "myBucket"] gives this workload full access to both resources and injects STP_MY_DATABASE_CONNECTION_STRING, STP_MY_BUCKET_NAME, etc.

properties.iamRoleStatements

Raw IAM policy statements for permissions not covered by connectTo.

Type: Array of StpIamRoleStatement

Added as a separate policy alongside auto-generated permissions. Use this for accessing AWS services directly (e.g., Rekognition, Textract, Bedrock).

overrides

Escape hatch to modify the underlying CloudFormation resources Stacktape creates.

Type: Object

Use dot-notation paths to override specific properties on any child resource. Find resource logical IDs with stacktape stack-info --detailed.

overrides:
  MyDbInstance:
    Properties.StorageEncrypted: true
NextjsServerLambdaPropertiesAPI referenceParent:NextjsWeb
memoryDefault: 1024

Memory in MB (128–10,240). CPU scales proportionally — 1,769 MB = 1 vCPU.

Type: number

timeoutDefault: 30

Max execution time in seconds. Max: 30.

Type: number

logging

Logging config. Logs are sent to CloudWatch. View with stacktape logs or in the AWS console.

Type: LambdaFunctionLogging

joinDefaultVpc

Connect to VPC resources (databases, Redis). Warning: function loses direct internet access.

Type: boolean

S3 and DynamoDB remain accessible via auto-created VPC endpoints.

LambdaFunctionLoggingAPI referenceParent:NextjsServerLambdaProperties
disabled

Disable CloudWatch logging entirely.

Type: boolean

retentionDaysDefault: 180

How many days to keep logs. Longer retention = higher storage cost.

Type: number ENUM

Possible values: 13571430609012015018036540054573118273653

logForwarding

Forward logs to an external service (Datadog, Highlight.io, or any HTTP endpoint).

Type: HttpEndpointLogForwarding or HighlightLogForwarding or DatadogLogForwarding

Uses Kinesis Data Firehose (~$0.03/GB). Failed deliveries go to a backup S3 bucket.

EnvironmentVarAPI referenceParent:NextjsWeb
nameRequired

Environment variable name (e.g., DATABASE_URL, API_KEY).

Type: string

valueRequired

Environment variable value. Numbers and booleans are converted to strings.

Type: string or number or boolean

DirectoryUploadFilterAPI referenceParent:NextjsWeb
includePatternRequired

Glob pattern for files this rule applies to (e.g., *.html, assets/**).

Type: string

excludePattern

Glob pattern for files to exclude even if they match includePattern.

Type: string

headers

HTTP headers (e.g., Cache-Control) for matching files. Forwarded through CDN to the browser.

Type: Array of KeyValuePair

tags

Tags for matching files. Can be used to target files with lifecycleRules.

Type: Array of KeyValuePair