# Deploying Next.js to Vercel

> Source: https://agilitycms.com/docs/nextjs/deploying-next-js-to-vercel

Vercel is built by the team behind Next.js, so every Next.js feature works there on the day it ships, including the proxy, on-demand revalidation and Cache Components. This guide covers deploying an Agility-powered Next.js site, wiring up publish-triggered updates, and the two settings that most often break preview after a successful deploy.

## Deploy via the Agility integration

The fastest path. In the Agility Manager, go to **Settings → Deployment** and click **Setup Deployment** for Vercel.

> **Note:** You'll need a GitHub account and a Vercel account.

The wizard then:

1. Authorizes the Agility integration with your Vercel account.
2. Creates (or connects) a Git repository and clones the starter into it.
3. Sets your `AGILITY_*` environment variables on the Vercel project, for both **Production** and **Preview**.
4. Builds and deploys.
5. Writes the resulting Production and Preview domains back into your Agility instance.

That last step is what makes preview work without you configuring anything: Agility now knows which URL to open when an editor clicks **Preview**.

## Deploy manually

If your project isn't based on a starter:

1. Push your repository to GitHub, GitLab or Bitbucket.
2. At [vercel.com/new](https://vercel.com/new), import it. Vercel detects Next.js and needs no build configuration.
3. Add your environment variables:

   | Variable | Purpose |
   |---|---|
   | `AGILITY_GUID` | Your instance identifier |
   | `AGILITY_API_FETCH_KEY` | Live (published) content |
   | `AGILITY_API_PREVIEW_KEY` | Draft content, for preview |
   | `AGILITY_SECURITY_KEY` | Validates preview links and webhooks |
   | `AGILITY_LOCALES` | Comma-separated, first is the default |
   | `AGILITY_SITEMAP` | Sitemap channel name, usually `website` |

   Set them for **Production, Preview and Development**. A missing key on Preview is the classic cause of "it works in production but every preview deploy 500s."

4. Deploy, then install the **Agility CMS** integration from the Vercel Marketplace to link the project back to your instance.

## Updating content without rebuilding

Don't rebuild the site on every publish. The [Agility Next.js Starter](https://github.com/agility/agilitycms-nextjs-starter) tags every Agility fetch with a cache tag, and a publish webhook invalidates exactly the tags that changed, so the update is live on the next request and nothing else re-renders.

Each read in the starter's `lib/cms/` helpers sets the tag on the fetch:

```ts
// lib/cms/getContentItem.ts (starter)
agilitySDK.config.fetchConfig = {
	next: {
		tags: [`agility-content-${params.contentID}-${params.languageCode || params.locale}`],
		revalidate: 60,
	},
}
```

and the starter's route handler clears those tags when Agility sends a publish event:

```ts
// app/api/revalidate/route.ts (starter, abridged)
import { revalidateTag } from "next/cache"
import { NextRequest, NextResponse } from "next/server"

export async function POST(req: NextRequest) {
	const data = await req.json()

	if (data.state === "Published") {
		if (data.referenceName) {
			// content item or list change
			revalidateTag(`agility-content-${data.referenceName}-${data.languageCode}`, "max")
			revalidateTag(`agility-content-${data.contentID}-${data.languageCode}`, "max")
		} else if (data.pageID > 0) {
			// page change: the page and the sitemaps
			revalidateTag(`agility-page-${data.pageID}-${data.languageCode}`, "max")
			revalidateTag(`agility-sitemap-flat-${data.languageCode}`, "max")
			revalidateTag(`agility-sitemap-nested-${data.languageCode}`, "max")
		}
	}

	return NextResponse.json({ message: "OK" }, { status: 200 })
}
```

> In Next.js 16, `revalidateTag` takes a second argument, the cache profile. `"max"` (recommended) serves the stale page while the fresh one renders in the background. The one-argument form is deprecated and TypeScript rejects it, so a typed project fails to build without it.

The endpoint is public, so check that each request really comes from Agility before you act on it. See [Verifying Signed Webhooks](/docs/developers/verifying-signed-webhooks).

If you've enabled [Cache Components](/docs/nextjs/caching-with-next-js-and-agility), the same webhook works: you tag reads with `cacheTag()` inside `"use cache"` functions instead of on the fetch.

### Point Agility at it

In the Manager, go to **Settings → Web Hooks** and add one pointing at `https://your-site.com/api/revalidate`. Check **Receive Content Publish Events**, and send a **Test Payload** to confirm you get a success response before relying on it.

If you want to trigger a full rebuild instead (appropriate only if you don't use tag revalidation), create a **Deploy Hook** in Vercel under **Settings → Git → Deploy Hooks** and point the Agility webhook at that URL.

## Making preview work on a deployed site

Two things bite here, and both only appear once the site is actually on Vercel.

### 1. Cached pages skip the proxy

Vercel serves prerendered pages straight from its edge cache **without invoking your proxy**. On exactly the pages that matter most, `?agilitypreviewkey=` never reaches `/api/preview`, draft mode is never enabled, and Web Studio quietly shows published content.

The fix is a `beforeFiles` rewrite, which is compiled into the routes manifest and evaluated *before* the cache lookup:

```js
// next.config.mjs
async rewrites() {
  return {
    beforeFiles: [
      {
        source: "/:path((?!api).*)",
        has: [{ type: "query", key: "agilitypreviewkey" }],
        destination: "/api/preview?slug=/:path",
      },
    ],
  }
}
```

Keep the proxy logic as well, since it handles uncached requests. Full detail in [Preview URL Lifecycle](/docs/nextjs/preview-url-lifecycle).

### 2. Deployment Protection blocks Agility

Vercel protects preview deployments by default. Agility's preview requests and your webhook calls arrive unauthenticated and get an SSO page instead of your site, so preview shows a Vercel login screen, and publishes appear not to revalidate.

Under **Settings → Deployment Protection**, either add a **Protection Bypass for Automation** secret and configure it in your Agility integration, or scope protection so the domain Agility calls is reachable. Don't simply switch protection off.

## Build settings worth checking

- **Node.js version:** new Vercel projects default to the latest Node.js LTS (24.x, the current Active LTS), which is what you want. Leave it there. If you need to pin it, set it under **Settings → Build and Deployment → Node.js Version**, or with `"engines": { "node": "24.x" }` in `package.json` (which overrides the project setting). Node 18 and 20 are end-of-life; Next.js 16 needs at least 20.9.
- **`prebuild`:** if your project syncs redirects or other data before building (npm runs `prebuild` automatically before `build`), confirm that step has the env vars it needs on Vercel, not just locally.
- **Build cache:** Vercel caches `.next/cache` between builds, which is what keeps incremental builds fast. Use **Redeploy without cache** when debugging a build that succeeds locally but not on Vercel.

## Verify the deployment

```bash
curl -I https://your-site.com/about-us                  # 200, with cache headers
curl -I https://your-site.com/no-such-page              # a real 404, not a 200
curl -X POST https://your-site.com/api/revalidate \
  -H "Content-Type: application/json" -d '{"state":"Published", ...}'
```

Then publish a change in Agility and confirm it appears on the live site within seconds. That end-to-end test is what actually proves the wiring.

## Summary

1. **Settings → Deployment** in Agility for the automated path; Vercel Marketplace integration for a manual one.
2. Set every `AGILITY_*` variable on **all three** environments.
3. Use tagged reads plus a publish webhook that calls `revalidateTag(tag, "max")`, instead of rebuilding on every publish.
4. Add the `beforeFiles` preview rewrite, or preview breaks on exactly the cached pages editors care about.
5. Deal with Deployment Protection deliberately, or Agility can't reach your preview deployments.

---

## Related pages

- [Multi-Locale Support with Next.js](https://agilitycms.com/docs/nextjs/multi-locale-support-with-next-js.md)
- [Google Analytics and Next.js](https://agilitycms.com/docs/nextjs/google-analytics-and-next-js.md)
- [Deploying Next.js to Netlify](https://agilitycms.com/docs/nextjs/deploying-next-js-to-netlify.md)
- [Deploying Next.js on Azure](https://agilitycms.com/docs/nextjs/deploying-next-js-on-azure.md)
- [Using Storybook.js with Agility CMS and Next.js](https://agilitycms.com/docs/nextjs/using-storybook-js-with-agility-cms-and-next-js.md)
- [Rendering & Data Fetching with Next.js](https://agilitycms.com/docs/nextjs/next-js-and-server-side-rendering.md)
- [Implementing Pagination with Next.js](https://agilitycms.com/docs/nextjs/implementing-pagination-with-next-js.md)
- [Implementing URL Redirects with Next.js](https://agilitycms.com/docs/nextjs/implementing-url-redirects-with-next-js.md)
- [Implementing a Custom 404 Page with Next.js](https://agilitycms.com/docs/nextjs/implementing-a-custom-404-page-with-next-js.md)
- [Implementing JSON-LD Structured Data with Next.js](https://agilitycms.com/docs/nextjs/implementing-json-ld-structured-data-with-next-js.md)
- [Using the AgilityPic Component for Responsive Images](https://agilitycms.com/docs/nextjs/using-the-agilitypic-component-for-responsive-images.md)

Index of every docs page: https://agilitycms.com/docs/llms.txt
