Next.js Zero to Advanced #12: Deploying to Production
Welcome to the final part of this series! In Part 11 we got DigiStore ready for production: error handling, SEO, a sitemap, security headers and an environment variable checklist. Now it is time to put DigiStore on the internet. In Part 12 we will push the code to GitHub, set up a managed PostgreSQL database, run prisma migrate deploy, deploy to Vercel, attach a custom domain, read the logs, and then close the series with a recap and next steps.
The Production Architecture
- GitHub stores the code. Every push to the
mainbranch triggers a production deploy. - Vercel runs
npm installandnpm run build, then serves static pages from its CDN and runs dynamic pages, Server Actions, Route Handlers and the proxy as functions. - Managed PostgreSQL (for example Neon or Supabase) stores the data. Backups, updates and server availability are handled by the provider.
The steps below are deliberately generic because every provider's dashboard changes often. The concepts stay the same with any provider.
Step 1: Push to GitHub
create-next-app already created a Git repository back in Part 1. Before pushing, make sure no secret files are included:
git status
git check-ignore .envThe correct result: git check-ignore prints .env, meaning the file is ignored. If it prints nothing, add .env to .gitignore first. If .env was ever committed, treat every secret in it as leaked and generate new ones. Once it is safe, create a new (private or public) repository on GitHub, then:
git add .
git commit -m "DigiStore: siap production"
git branch -M main
git remote add origin https://github.com/your-username/digistore.git
git push -u origin mainStep 2: Setting Up Managed PostgreSQL
- Sign up with your managed PostgreSQL provider of choice and create a new project/database named
digistorewith PostgreSQL 16 or newer. - Pick a region close to your Vercel function region (for example both in Singapore). A long distance between the app and the database adds latency to every query.
- Copy the connection strings from the dashboard. Many providers offer two kinds: pooled (through a connection pooler) and direct (straight to the database).
They look roughly like this. The values below are examples only; never paste a real connection string into code, chats or screenshots:
# Example format only, not real credentials
DATABASE_URL="postgresql://db_user:YOUR_PASSWORD@pooler.db.example.com:6543/digistore?sslmode=require&pgbouncer=true"
DIRECT_URL="postgresql://db_user:YOUR_PASSWORD@db.example.com:5432/digistore?sslmode=require"Why does connection pooling matter?
On a regular server, the app opens a few database connections and keeps reusing them. On a serverless platform, dozens of function instances can run at once when traffic spikes, and each one opens its own connections. PostgreSQL has a connection limit, so without a pooler the database may start refusing new connections. A pooler (for example PgBouncer) accepts many connections from the app and forwards them over a few connections to the database. The lib/prisma.ts singleton from Part 6 still helps because it stops one instance from creating many clients.
A transaction-mode pooler does not support every command that migrations need. So with Prisma 6 we use the pooled URL for the app and the direct URL for migrations through directUrl. This is an optional change to the Part 6 setup: if your provider only gives one URL without a pooler, skip the rest of this subsection and keep using DATABASE_URL alone. The exact parameters (for example pgbouncer=true or connection_limit) differ between providers, so follow the "Prisma" guide in your provider's docs.
Remember that since Part 6 the Prisma CLI gets its connection from prisma.config.ts (engine: 'classic' plus a datasource block). In Prisma 6 that datasource overrides the URL attributes of the datasource block in schema.prisma. So directUrl must be added in prisma.config.ts; if you only add it to the schema, the CLI ignores it and migrate deploy still goes through the pooler:
// prisma.config.ts (from Part 6, only the datasource block changes)
import 'dotenv/config'
import { defineConfig, env } from 'prisma/config'
export default defineConfig({
schema: 'prisma/schema.prisma',
migrations: {
path: 'prisma/migrations',
seed: 'tsx prisma/seed.ts',
},
engine: 'classic',
datasource: {
url: env('DATABASE_URL'), // pooled URL
directUrl: env('DIRECT_URL'), // direct URL, used by migrate
},
})Also add the same line to the Part 6 schema so it keeps describing the real connection setup (the CLI takes the actual values from the config):
// prisma/schema.prisma (optional, only the datasource block changes)
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
directUrl = env("DIRECT_URL")
}Because env('DIRECT_URL') in the config throws an error when the variable is missing, also set DIRECT_URL in your local .env (it can equal your local DATABASE_URL), in .env.example, and in Vercel. Everything else from Part 6 stays the same: the seed command remains under migrations.seed, and import 'dotenv/config' still loads your local .env for the CLI.
Step 3: Migrations in Production
During development we used prisma migrate dev. That command creates new migration files and may offer to reset the database, so never run it against production. For production there is prisma migrate deploy: it only applies migration files in prisma/migrations that have not been recorded yet, without creating new migrations and without deleting data. That is why the prisma/migrations folder must be committed.
prisma generate in the build
Prisma Client is code generated from schema.prisma. Vercel caches node_modules between deploys, so a stale client could be used even after the schema changed. The fix: run prisma generate in postinstall and at the start of build.
Option A: Migrations inside the build script
{
"scripts": {
"dev": "next dev",
"build": "prisma generate && prisma migrate deploy && next build",
"start": "next start",
"postinstall": "prisma generate"
}
}Keep your other scripts (such as lint). There is no "prisma" key to add to package.json: the seed command stays in prisma.config.ts from Part 6. On Vercel there is no .env file, so import 'dotenv/config' in that config simply loads nothing, and the Prisma CLI reads DATABASE_URL (and DIRECT_URL, if you use it) from the environment variables you set in the Vercel dashboard. The order matters: migrations run before next build, because sitemap.ts from Part 11 reads the Product table during the build.
Option B: Migrations as a separate step
The build script only contains prisma generate && next build, and prisma migrate deploy runs separately, for example in a CI workflow (GitHub Actions) before the deploy, or manually from a terminal with the production DATABASE_URL loaded from a secret manager.
| Option A: in build | Option B: separate | |
|---|---|---|
| Pros | Simple, you can never forget a migration. | Full control: migrations can be reviewed, scheduled and tested first. |
| Risks | Every build, including Previews, touches the database DATABASE_URL points to. If the build fails after migrating, the database has changed while the old code is still live. | Needs CI setup or manual discipline; the order of migration and deploy must be managed. |
| Best for | Personal projects and small teams like DigiStore. | Teams, important data, large migrations. |
For this series we use Option A, with two safety rules: (1) Preview deployments use a separate database, never the production one; (2) write backward-compatible migrations, for example add a new column first, deploy the code that uses it, and only drop the old column in a later migration.
Step 4: Deploy on Vercel
- Log in to Vercel with your GitHub account, choose Add New Project, then import the
digistorerepository. The Next.js framework is detected automatically. - In the project settings, make sure the Node.js version is 20 or newer, and set the function region close to your database.
- Open Environment Variables and fill in the variables from the Part 11 checklist, scoped to Production.
- Click Deploy and watch the build log.
| Variable | Production value |
|---|---|
DATABASE_URL | Pooled URL from the database provider |
DIRECT_URL | Direct URL (if you use directUrl) |
SESSION_SECRET | A new secret from openssl rand -base64 32, different from your local one |
SITE_URL | https://digistore.example.com (or the temporary .vercel.app URL) |
Do not add SEED_ADMIN_PASSWORD to Vercel because the seed does not run on the server. A successful build log contains roughly:
> prisma generate && prisma migrate deploy && next build
Generated Prisma Client to ./node_modules/@prisma/client
1 migration found in prisma/migrations
Applying migration `20261001000000_init`
All migrations have been successfully applied.
β² Next.js 16.x
Creating an optimized production build ...
β Compiled successfullyStep 5: Creating the Admin Account in Production
The production database is still empty. The Part 6 seed contains demo data and test accounts, so do not run it against production carelessly. A safer approach:
- Open your site and register through
/registerwith your email. New accounts always get the USER role. - Open the SQL editor in your database provider's dashboard, then promote that account:
UPDATE "User" SET role = 'ADMIN' WHERE email = 'admin@example.com';Log out and log in again. This matters: requireAdmin() reads the role from the database so it sees the change immediately, but proxy.ts reads the role from the JWT in the cookie. Your old token still says USER until you log in again. After that, add real products via /admin/products.
Step 6: A Custom Domain
- In Vercel, open Settings β Domains and add your domain, for example
digistore.example.com. - Vercel shows the DNS records (A or CNAME) you need to add at your domain registrar. DNS changes can take from a few minutes to a few hours.
- The HTTPS certificate is issued automatically. The
securecookie and the HSTS header from Part 11 are now fully in effect. - Change
SITE_URLto the new domain and redeploy, so canonical URLs, Open Graph and the sitemap use the right domain.
Step 7: Smoke Test, Logs and Rollback
After every significant deploy, run through this quick check:
- The home page, the catalog with search and filters, and the product detail page render normally.
- Register, log in, buy a product, then the order appears in
/orders. - A regular user cannot open
/admin/products, and acurl -X POSTto/api/productswithout a cookie gets 401. /sitemap.xmland/robots.txtuse the production domain.
curl -I https://digistore.example.comMake sure the headers from Part 11 (x-frame-options, strict-transport-security and the rest) are present. If a user reports an error page, ask for the error code (digest) that error.tsx shows. Open the Logs tab in your Vercel project and filter by time or search for that digest to find the real server-side stack trace. Build logs live in each deployment's details, while runtime logs contain console.error output from Server Components, Server Actions and Route Handlers. Never print passwords, tokens or cookie contents to the logs.
If a new deploy misbehaves, you can roll back to a previous deployment from the Deployments page without rebuilding. Remember that rolling back code does not undo database migrations; that is exactly why migrations must be backward compatible.
Common Mistakes
- Running
prisma migrate devormigrate resetagainst the production database. Usemigrate deploy. - Forgetting to commit the
prisma/migrationsfolder, so the production build finds no migrations. - Reusing the development
SESSION_SECRET, or sharing it over chat. - Preview deployments pointing at the production database, so migrations or test data from feature branches hit real data.
- Forgetting to update
SITE_URL, so canonical URLs and the sitemap still saylocalhost. - Not using the pooled URL on serverless, which leads to "too many connections" errors when traffic spikes.
Exercises
- Create a second database for Previews, set a Preview-scoped
DATABASE_URLin Vercel, then open a small pull request and confirm its preview uses that database. - Switch to Option B: create a GitHub Actions workflow that runs
npm ciandnpx prisma migrate deploywithDATABASE_URLfrom GitHub Secrets, then removeprisma migrate deployfrom the build script. - Add a new optional column (for example
downloadUrl String?onProduct), create the migration locally, push, then watch it get applied in the production build log.
Series Recap
Congratulations, you have built and shipped a full-stack app from scratch! Here is the journey:
| Part | Topic |
|---|---|
| 1β2 | Project setup, App Router, routing, layouts, navigation |
| 3β4 | Server and Client Components, Tailwind CSS, next/image, next/font |
| 5β7 | PostgreSQL, Prisma (schema, migrations, seed), fetching data from the database |
| 8β9 | Server Actions with zod validation, Route Handlers for a REST API |
| 10 | Authentication, authorization, proxy.ts, IDOR prevention |
| 11β12 | Error handling, SEO, security headers, production deployment |
Where to Go Next
- Testing: unit tests for
lib/validation.tsandlib/session.ts, plus end-to-end tests for the login and purchase flows. - Advanced security: rate limiting on login, a Content Security Policy, email verification and password reset.
- Business features: a real payment gateway, download links only buyers can access, and product image uploads.
- Database: learn about indexes and query performance in the PostgreSQL Zero to Advanced series, especially as products and orders grow.
- Compare other frameworks: see how Rails handles sessions and authentication in the Ruby on Rails Zero to Advanced series.
If you grow DigiStore or another project into a polished template or source code package, you can sell it on the FullstackNotes marketplace. Sign up as a seller on the Become a Seller page.
Summary
- Make sure
.envnever enters Git; commitprisma/migrationsand.env.example. - Use managed PostgreSQL with a pooled URL for the app and a direct URL (
directUrlinprisma.config.ts) for migrations. prisma generateinpostinstalland the build;prisma migrate deployin the build (Option A) or in CI (Option B).- Set
DATABASE_URL, a newSESSION_SECRETandSITE_URLin Vercel; keep Preview and Production databases separate. - Attach a domain, run a smoke test, use the digest to find errors in the logs, and roll back when needed.
Thank you for following the "Next.js Zero to Advanced" series all the way to the end. DigiStore is now online, secure and ready for you to extend. Happy building!
Related articles
PostgreSQL Zero to Advanced #1: Introduction & Setup
Start the series by understanding what a relational database is, installing PostgreSQL locally, and getting comfortable with psql commands like \l, \c and \dt.
PHP Zero to Advanced #8: Composer, Namespaces, PSR-4 Autoloading & Exceptions
Structure real PHP projects: organize code with namespaces, manage dependencies with Composer, autoload classes with PSR-4, and handle errors cleanly with exceptions.
Ruby on Rails Zero to Advanced #8: Forms, Strong Parameters & Full CRUD
Build a complete CRUD feature by hand with form_with and strong parameters, then compare it with what rails generate scaffold gives you for free.