Quick Nextjs Deploy

Posted on October 2, 2021
Tags: javascript

1 Stripping nextjs to minimum runtime

{
  "name": "my-app",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "",
    "build": "",
    "start": "node server.js",
    "lint": "next lint"
  },
  "dependencies": {
    "next": "13.0.5"
  }
}

1.1 Standalone mode

  • add output: 'standalone', to nextconfig object in next.config.js
    • this will create a standalone folder /myapp/.next/standalone
  • copy /myapp/.next/static into /myapp/.next/standalone/.next
  • copy /myapp/public into /myapp/.next/standalone/public
npm run build
cp -r /myapp/.next/static /myapp/.next/standalone/.next
cp -r /myapp/public /myapp/.next/standalone/public
node /myapp/.next/standalone/server.js

TO RUN:
call node /myapp/.next/standalone/server.js

1.1.1 standalone package.json

Instead of doing the above steps, we can modify package.json to do it for us.

{
  "name": "my-app",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "standalonebuild": "cp -r .next/static .next/standalone/.next && cp -r public .next/standalone/.next",
    "execstandalone" : "node .next/standalone/server.js",
    "dev": "next dev",
    "build": "next build && npm run standalone",
    "start": "next start",
    "lint": "next lint"
  },
  "dependencies": {
    "next": "13.0.5",
    ...
  }
}

TO RUN:

npm run build 
npm run execstandalone

2 AWS Amplify

The below gets autodetected for a typical vanilla nextjs repo

version: 1
frontend:
  phases:
    preBuild:
      commands:
        - npm ci
    build:
      commands:
        - npm run build
  artifacts:
    baseDirectory: .next
    files:
      - '**/*'
  cache:
    paths:
      - node_modules/**/*

2.1 NX monorepo

Here the autodetection doesnt work.
Instead we must run nextjs as standalone mode.