### Next.js Middleware Configuration
Source: https://github.com/cloudflare/next-on-pages/blob/main/packages/next-on-pages/docs/examples.md
An example of Next.js middleware, used for intercepting requests and performing actions like redirects. This example redirects all requests for '/about/:path*' to '/home'. It specifies the routes to match using the `matcher` in `config`.
```typescript
// ./middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
// This function can be marked `async` if using `await` inside
export function middleware(request: NextRequest) {
return NextResponse.redirect(new URL('/home', request.url));
}
export const config = {
matcher: '/about/:path*',
};
```
--------------------------------
### Install @cloudflare/next-on-pages
Source: https://github.com/cloudflare/next-on-pages/blob/main/packages/next-on-pages/README.md
This command installs the `@cloudflare/next-on-pages` package as a development dependency in your Next.js project. This is a prerequisite for deploying your application to Cloudflare Pages.
```sh
npm install -D @cloudflare/next-on-pages
```
--------------------------------
### Install ESLint Plugin for Next-on-Pages
Source: https://context7.com/cloudflare/next-on-pages/llms.txt
This bash command installs the ESLint plugin for next-on-pages as a development dependency. Ensure the version matches your next-on-pages installation to maintain compatibility.
```bash
# Install ESLint plugin (same version as next-on-pages)
npm install --save-dev eslint-plugin-next-on-pages@1.13.16
```
--------------------------------
### Create and Navigate to Next.js App
Source: https://github.com/cloudflare/next-on-pages/blob/main/packages/next-on-pages/README.md
This snippet demonstrates how to create a new Next.js application using `create-next-app` and then navigate into the project directory. This is a common setup step before configuring for Cloudflare Pages.
```sh
npx create-next-app@latest my-next-app
cd my-next-app
```
--------------------------------
### SSR Pages with getServerSideProps on Edge Runtime
Source: https://github.com/cloudflare/next-on-pages/blob/main/packages/next-on-pages/docs/examples.md
An example of a Server-Side Rendering page in the Pages Directory that uses `getServerSideProps` and is configured to run on the Edge Runtime. It fetches a UUID and displays the runtime environment.
```typescript
// ./pages/ssr.tsx
import styles from '../styles/Home.module.css';
export const config = {
runtime: 'edge',
};
export const getServerSideProps = async () => {
return {
props: {
runtime: process.env.NEXT_RUNTIME,
uuid: await fetch('https://uuid.rocks/plain').then(response =>
response.text(),
),
},
};
};
type Props = { runtime: string; uuid: string };
export default function Page({ runtime, uuid }: Props) {
return (
Here's a server-side UUID:
{uuid}
);
}
```
--------------------------------
### Valid Non-Existing Config Example (ESLint)
Source: https://github.com/cloudflare/next-on-pages/blob/main/packages/eslint-plugin-next-on-pages/docs/rules/no-unsupported-configs.md
This example shows a `next.config.mjs` with a `nonExistingConfig` property, which is considered valid by the ESLint rule when not specifically configured to report unrecognized options.
```javascript
// eslintrc
"next-on-pages/no-unsupported-configs": "error"
// next.config.mjs
/** @type {import('next').NextConfig} */
const nextConfig = {
nonExistingConfig: 'test',
}
export default nextConfig
```
--------------------------------
### Install ESLint Plugin for Next-on-Pages
Source: https://github.com/cloudflare/next-on-pages/blob/main/packages/eslint-plugin-next-on-pages/README.md
Installs the eslint-plugin-next-on-pages using npm. Ensure the version (V) matches your @cloudflare/next-on-pages package version for optimal compatibility.
```sh
npm i --save-dev eslint-plugin-next-on-pages@V
```
--------------------------------
### Setup Local Dev Platform Simulation (JavaScript)
Source: https://context7.com/cloudflare/next-on-pages/llms.txt
Configures the Next.js development server to simulate Cloudflare platform resources locally, enabling developers to test integrations with Cloudflare services during the development phase. This is typically done in the `next.config.mjs` file.
```javascript
// next.config.mjs
import { setupDevPlatform } from '@cloudflare/next-on-pages/next-dev';
/** @type {import('next').NextConfig} */
const nextConfig = {
// Your Next.js configuration
};
export default nextConfig;
// Setup Cloudflare platform simulation in development
if (process.env.NODE_ENV === 'development') {
await setupDevPlatform();
}
```
--------------------------------
### Example wrangler.toml for Cloudflare Bindings
Source: https://github.com/cloudflare/next-on-pages/blob/main/internal-packages/next-dev/README.md
A sample wrangler.toml file demonstrating how to declare various Cloudflare bindings, including KV namespaces, R2 buckets, and Durable Objects. These declarations are used by the next-dev utility to simulate the production environment during local development.
```toml
[[kv_namespaces]]
binding = "MY_KV_1"
id = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
[[kv_namespaces]]
binding = "MY_KV_2"
id = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
[[durable_objects.bindings]]
name = "MY_DO"
script_name = "do-worker"
class_name = "DurableObjectClass"
[[r2_buckets]]
binding = "MY_R2"
bucket_name = "my-bucket"
```
--------------------------------
### Server-Side Rendering with Edge Runtime in Next.js App Directory
Source: https://github.com/cloudflare/next-on-pages/blob/main/packages/next-on-pages/docs/examples.md
An example of a Server-Side Rendering (SSR) page using the Edge Runtime within the App Directory. It displays the `searchParams` received by the page. The `runtime` must be set to 'edge'.
```typescript
// ./app/ssr/page.tsx
export const runtime = 'edge';
export default async function Page({ searchParams }: { searchParams: any }) {
return (
Updating searchParams
searchParams is {JSON.stringify(searchParams)}
);
}
```
--------------------------------
### Edge Route Handlers in Next.js App Directory
Source: https://github.com/cloudflare/next-on-pages/blob/main/packages/next-on-pages/docs/examples.md
An example of an Edge Runtime API route handler within the App Directory structure of Next.js. It demonstrates accessing cookies and setting a response header. Requires `next/headers`.
```typescript
// ./app/api/hello/route.ts
import { cookies } from 'next/headers';
export const runtime = 'edge';
export async function GET(request: Request) {
const cookieStore = cookies();
const token = cookieStore.get('token');
return new Response('Hello, Next.js!', {
status: 200,
headers: { 'Set-Cookie': `token=${token}` },
});
}
```
--------------------------------
### Edge API Routes in Next.js Pages Directory
Source: https://github.com/cloudflare/next-on-pages/blob/main/packages/next-on-pages/docs/examples.md
An example of an Edge Runtime API route in the Pages Directory. It utilizes the `config` object to specify the 'edge' runtime and returns a JSON response including the `NEXT_RUNTIME` environment variable.
```typescript
// ./pages/api/some_route.ts
import type { NextRequest } from 'next/server';
export const config = {
runtime: 'edge',
};
export default async function handler(req: NextRequest) {
return new Response(
JSON.stringify({
name: process.env.NEXT_RUNTIME,
}),
{
status: 200,
headers: {
'content-type': 'application/json',
},
},
);
}
```
--------------------------------
### Valid next.config.mjs with Page Extensions (ESLint)
Source: https://github.com/cloudflare/next-on-pages/blob/main/packages/eslint-plugin-next-on-pages/docs/rules/no-unsupported-configs.md
This example shows a valid `next.config.mjs` configuration where `pageExtensions` is used, demonstrating that the ESLint rule does not flag supported options.
```javascript
// eslintrc
"next-on-pages/no-unsupported-configs": "error"
// next.config.mjs
/** @type {import('next').NextConfig} */
const nextConfig = {
pageExtensions: ['page.tsx'],
}
export default nextConfig
```
--------------------------------
### Configure Next.js for Local Cloudflare Development with setupDevPlatform
Source: https://github.com/cloudflare/next-on-pages/blob/main/internal-packages/next-dev/README.md
Integrates the setupDevPlatform utility into your Next.js configuration file (next.config.mjs or next.config.(c)js) to enable local Cloudflare platform simulation during development. This function reads wrangler.toml to provide bindings via getRequestContext. Ensure @cloudflare/next-on-pages is installed.
```javascript
// file: next.config.mjs
// we import the utility from the next-dev submodule
import { setupDevPlatform } from '@cloudflare/next-on-pages/next-dev';
/** @type {import('next').NextConfig} */
const nextConfig = {};
export default nextConfig;
// we only need to use the utility during development so we can check NODE_ENV
// (note: this check is recommended but completely optional)
if (process.env.NODE_ENV === 'development') {
// `await`ing the call is not necessary but it helps making sure that the setup has succeeded.
// If you cannot use top level awaits you could use the following to avoid an unhandled rejection:
// `setupDevPlatform().catch(e => console.error(e));`
await setupDevPlatform();
}
```
--------------------------------
### Next.js App Router API Route with Edge Runtime
Source: https://context7.com/cloudflare/next-on-pages/llms.txt
An example of an API route using the Next.js App Router configured for the edge runtime. It demonstrates handling GET and POST requests, accessing cookies, and setting response headers. This route is suitable for deployment on Cloudflare Pages.
```typescript
// app/api/hello/route.ts
import { cookies } from 'next/headers';
export const runtime = 'edge';
export async function GET(request: Request) {
const cookieStore = cookies();
const token = cookieStore.get('token');
return new Response('Hello, Next.js!', {
status: 200,
headers: {
'Set-Cookie': `token=${token?.value || 'new-token'}`,
'Content-Type': 'text/plain'
},
});
}
export async function POST(request: Request) {
const body = await request.json();
return Response.json({
message: 'Data received',
data: body,
timestamp: Date.now()
});
}
```
--------------------------------
### Valid getStaticPaths with fallback: 'blocking' and edge runtime
Source: https://github.com/cloudflare/next-on-pages/blob/main/packages/eslint-plugin-next-on-pages/docs/rules/no-pages-nodejs-dynamic-ssg.md
This code snippet demonstrates a valid setup for `getStaticPaths` using the 'edge' runtime. The `fallback: 'blocking'` option is allowed when the `runtime` is explicitly set to `experimental-edge`, supporting dynamic SSG.
```javascript
export async function getStaticPaths() {
return {
paths: // ...
fallback: 'blocking'
};
}
export const runtime = 'experimental-edge';
// ...
```
--------------------------------
### Handle Unsupported Trailing Slash Config (ESLint)
Source: https://github.com/cloudflare/next-on-pages/blob/main/packages/eslint-plugin-next-on-pages/docs/rules/no-unsupported-configs.md
This example illustrates how the ESLint rule flags the `trailingSlash` configuration when it's set to `true` and unsupported, showing the invalid configuration in `next.config.mjs`.
```javascript
// eslintrc
"next-on-pages/no-unsupported-configs": "error"
// next.config.mjs
/** @type {import('next').NextConfig} */
const nextConfig = {
trailingSlash: true,
~~~~~~~~~~~~~ // Indicates an unsupported option is flagged here
}
export default nextConfig
```
--------------------------------
### Valid Trailing Slash Config with Rule Option (ESLint)
Source: https://github.com/cloudflare/next-on-pages/blob/main/packages/eslint-plugin-next-on-pages/docs/rules/no-unsupported-configs.md
This example demonstrates a valid `next.config.mjs` configuration for `trailingSlash` when the ESLint rule option `includeCurrentlyUnsupported` is set to `false`, allowing the option.
```javascript
// eslintrc
"next-on-pages/no-unsupported-configs": [
"error", { includeCurrentlyUnsupported: false }
]
// next.config.mjs
/** @type {import('next').NextConfig} */
const nextConfig = {
trailingSlash: true,
}
export default nextConfig
```
--------------------------------
### Opting Routes into Edge Runtime in Next.js
Source: https://github.com/cloudflare/next-on-pages/blob/main/packages/next-on-pages/docs/examples.md
Demonstrates how to explicitly set the runtime for a Next.js route to 'edge'. This is achieved by exporting a `runtime` constant with the value 'edge'. Prior to Next.js v13.3.1, this was done via a `config` object.
```diff
+ export const runtime = 'edge';
```
```diff
export const config = {
+ runtime: 'edge',
};
```
--------------------------------
### Invalid getStaticPaths fallback: 'blocking'
Source: https://github.com/cloudflare/next-on-pages/blob/main/packages/eslint-plugin-next-on-pages/docs/rules/no-pages-nodejs-dynamic-ssg.md
This code snippet shows an invalid setup where `getStaticPaths` is configured with `fallback: 'blocking'` without specifying the 'edge' runtime. This configuration is not supported for dynamic SSG in Node.js environments on Cloudflare Pages.
```javascript
export async function getStaticPaths() {
return {
paths: // ...
fallback: 'blocking'
~~~~~~~~~~
};
}
// ...
```
--------------------------------
### Next.js Pages Router API Route with Edge Runtime and Bindings
Source: https://context7.com/cloudflare/next-on-pages/llms.txt
An API route for the Next.js Pages Router, configured to run on the edge runtime and interact with Cloudflare bindings. This example demonstrates fetching user data from KV cache, falling back to D1 database if not found, and caching the result in KV. It also includes error handling.
```typescript
// pages/api/user.ts
import type { NextRequest } from 'next/server';
import { getRequestContext } from '@cloudflare/next-on-pages';
export const config = {
runtime: 'edge',
};
export default async function handler(req: NextRequest) {
const { env, ctx } = getRequestContext();
const url = new URL(req.url);
const userId = url.searchParams.get('id');
if (!userId) {
return new Response(
JSON.stringify({ error: 'User ID required' }),
{
status: 400,
headers: { 'content-type': 'application/json' },
}
);
}
try {
// Check cache first
const cached = await env.MY_KV.get(`user:${userId}`);
if (cached) {
return new Response(cached, {
status: 200,
headers: {
'content-type': 'application/json',
'x-cache': 'HIT'
},
});
}
// Fetch from database
const user = await env.MY_DB
.prepare('SELECT * FROM users WHERE id = ?')
.bind(userId)
.first();
if (!user) {
return new Response(
JSON.stringify({ error: 'User not found' }),
{ status: 404, headers: { 'content-type': 'application/json' } }
);
}
// Cache the result
const userData = JSON.stringify(user);
ctx.waitUntil(
env.MY_KV.put(`user:${userId}`, userData, {
expirationTtl: 3600
})
);
return new Response(userData, {
status: 200,
headers: {
'content-type': 'application/json',
'x-cache': 'MISS'
},
});
} catch (error) {
return new Response(
JSON.stringify({ error: 'Internal server error' }),
{ status: 500, headers: { 'content-type': 'application/json' } }
);
}
}
```
--------------------------------
### Define Cloudflare Environment Bindings in TypeScript
Source: https://github.com/cloudflare/next-on-pages/blob/main/internal-packages/next-dev/README.md
Creates a TypeScript declaration file (env.d.ts) to strongly type your Cloudflare environment bindings, matching the interface used by getRequestContext. This requires installing @cloudflare/workers-types as a dev dependency and configuring your tsconfig.json.
```typescript
// file: env.d.ts
interface CloudflareEnv {
MY_KV_1: KVNamespace;
MY_KV_2: KVNamespace;
MY_R2: R2Bucket;
MY_DO: DurableObjectNamespace;
}
```
--------------------------------
### Valid generateStaticParams with dynamicParams=false in Next.js
Source: https://github.com/cloudflare/next-on-pages/blob/main/packages/eslint-plugin-next-on-pages/docs/rules/no-app-nodejs-dynamic-ssg.md
This code snippet illustrates a valid setup for `generateStaticParams` by exporting `dynamicParams` set to `false`. This configuration is essential for Next.js applications using `generateStaticParams` on Cloudflare Pages, ensuring proper handling of dynamic routes.
```javascript
export const dynamicParams = false;
export async function generateStaticParams() {
// ...
}
// ...
```
--------------------------------
### Next.js App Router SSR with Cloudflare Bindings
Source: https://context7.com/cloudflare/next-on-pages/llms.txt
Implements server-side rendering for a Next.js App Router page that fetches data from a D1 database and utilizes Cloudflare's edge request context (CF object). This example shows how to dynamically query the database based on search parameters and display user location information.
```typescript
// app/products/page.tsx
import { getRequestContext } from '@cloudflare/next-on-pages';
export const runtime = 'edge';
interface Product {
id: number;
name: string;
price: number;
}
export default async function ProductsPage({
searchParams,
}: {
searchParams: { category?: string };
}) {
const { env, cf } = getRequestContext();
// Fetch products from D1 database
const category = searchParams.category || 'all';
const query = category === 'all'
? 'SELECT * FROM products LIMIT 50'
: 'SELECT * FROM products WHERE category = ? LIMIT 50';
const stmt = category === 'all'
? env.MY_DB.prepare(query)
: env.MY_DB.prepare(query).bind(category);
const { results } = await stmt.all();
// Get user's location from Cloudflare
const userCountry = cf?.country || 'Unknown';
const userCity = cf?.city || 'Unknown';
return (
Products - {category}
Served from {userCity}, {userCountry}
{results.map((product) => (
-
{product.name} - ${product.price}
))}
);
}
```
--------------------------------
### Pages Router SSR with getServerSideProps (TypeScript)
Source: https://context7.com/cloudflare/next-on-pages/llms.txt
Implements server-side rendering in a Next.js Pages Router application using the edge runtime on Cloudflare Pages. It fetches data from Cloudflare KV and external APIs, and accesses Cloudflare request properties. This example requires the '@cloudflare/next-on-pages' package.
```typescript
// pages/profile.tsx
import { getRequestContext } from '@cloudflare/next-on-pages';
export const config = {
runtime: 'edge',
};
export const getServerSideProps = async () => {
const { env, cf } = getRequestContext();
// Fetch user session from KV
const session = await env.MY_KV.get('session:current', 'json');
// Get fresh data
const uuid = await fetch('https://uuid.rocks/plain')
.then(response => response.text());
// Access Cloudflare properties
const requestInfo = {
country: cf?.country,
city: cf?.city,
timezone: cf?.timezone,
asn: cf?.asn,
};
return {
props: {
runtime: process.env.NEXT_RUNTIME,
uuid,
session,
requestInfo,
},
};
};
interface Props {
runtime: string;
uuid: string;
session: any;
requestInfo: {
country?: string;
city?: string;
timezone?: string;
asn?: number;
};
}
export default function ProfilePage({ runtime, uuid, session, requestInfo }: Props) {
return (
Profile - Running on {runtime} runtime
Your Location
Country: {requestInfo.country}
City: {requestInfo.city}
Timezone: {requestInfo.timezone}
{session && (
User Data
{JSON.stringify(session, null, 2)}
)}
);
}
```
--------------------------------
### Build Next.js App for Cloudflare Pages (CLI)
Source: https://context7.com/cloudflare/next-on-pages/llms.txt
Builds and bundles a Next.js application for deployment to Cloudflare Pages. Options include watch mode, custom output directories, custom entrypoints for observability, skipping minification, and local preview.
```bash
npx @cloudflare/next-on-pages
npx @cloudflare/next-on-pages --watch
npx @cloudflare/next-on-pages --outdir=./dist
npx @cloudflare/next-on-pages --custom-entrypoint=./custom-entrypoint.ts
npx @cloudflare/next-on-pages --no-minify
npx @cloudflare/next-on-pages
npx wrangler pages dev .vercel/output/static --compatibility-flag=nodejs_compat
```
--------------------------------
### Preview Next.js App Locally with Wrangler
Source: https://github.com/cloudflare/next-on-pages/blob/main/packages/next-on-pages/README.md
Preview your built Next.js application locally using Cloudflare's `workerd` JavaScript runtime. Ensure you enable Node.js compatibility via `nodejs_compat` flag.
```sh
npx wrangler pages dev .vercel/output/static --compatibility-flag=nodejs_compat
```
--------------------------------
### Build Next.js App with Cloudflare
Source: https://github.com/cloudflare/next-on-pages/blob/main/packages/next-on-pages/README.md
Build your Next.js application to ensure compatibility with Cloudflare Pages. This command prepares your application for local preview and deployment.
```sh
npx @cloudflare/next-on-pages
```
--------------------------------
### Report Unrecognized Configs with Options (ESLint)
Source: https://github.com/cloudflare/next-on-pages/blob/main/packages/eslint-plugin-next-on-pages/docs/rules/no-unsupported-configs.md
This snippet demonstrates configuring the `next-on-pages/no-unsupported-configs` rule to report unrecognized configuration options by setting `includeUnrecognized` to `true` in the ESLint configuration.
```javascript
// eslintrc
"next-on-pages/no-unsupported-configs": [
"error", { "includeUnrecognized": true }
]
// next.config.mjs
/** @type {import('next').NextConfig} */
const nextConfig = {
nonExistingConfig: 'test',
~~~~~~~~~~~~~~~~~ // Indicates an unrecognized option is flagged here
}
export default nextConfig
```
--------------------------------
### Build and Preview Next.js App Locally with Wrangler
Source: https://github.com/cloudflare/next-on-pages/blob/main/internal-packages/next-dev/README.md
Build your Next.js application using '@cloudflare/next-on-pages' and preview it locally with Cloudflare's 'workerd' runtime via 'wrangler pages dev'. This command ensures your application is compatible with Cloudflare Pages and allows for local testing before deployment.
```bash
wrangler pages dev .vercel/output/static --compatibility-flag nodejs_compat
```
--------------------------------
### Deploy Next.js App with Wrangler CLI
Source: https://github.com/cloudflare/next-on-pages/blob/main/packages/next-on-pages/README.md
This command demonstrates how to publish a built Next.js application to Cloudflare Pages using the Wrangler CLI. This is an alternative to Git integration and requires the build output directory to be specified.
```sh
wrangler pages publish .vercel/output/static --project-name my-next-app
```
--------------------------------
### Configure Cloudflare Bindings with wrangler.toml
Source: https://context7.com/cloudflare/next-on-pages/llms.txt
Defines various Cloudflare services like KV namespaces, D1 databases, R2 buckets, and Durable Objects as bindings in the `wrangler.toml` configuration file. These bindings are essential for your application to interact with Cloudflare's services.
```toml
name = "my-next-app"
[[kv_namespaces]]
binding = "MY_KV"
id = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
[[d1_databases]]
binding = "MY_DB"
database_name = "my-database"
database_id = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
[[r2_buckets]]
binding = "MY_R2"
bucket_name = "my-bucket"
[[durable_objects.bindings]]
name = "MY_DO"
script_name = "do-worker"
class_name = "DurableObjectClass"
```
--------------------------------
### Custom Worker Entrypoint for Observability (TypeScript & Bash)
Source: https://context7.com/cloudflare/next-on-pages/llms.txt
Wraps the next-on-pages handler with custom logic for monitoring and observability in a Cloudflare Worker. It logs incoming requests, successful responses, and errors, and adds custom headers. The build command shows how to integrate this custom entrypoint during the build process.
```typescript
// custom-entrypoint.ts
import nextOnPagesHandler from '@cloudflare/next-on-pages/fetch-handler';
export default {
async fetch(request, env, ctx) {
const startTime = Date.now();
// Log incoming request
console.log('[Request]', {
method: request.method,
url: request.url,
headers: Object.fromEntries(request.headers),
timestamp: new Date().toISOString(),
});
try {
// Run next-on-pages handler
const response = await nextOnPagesHandler.fetch(request, env, ctx);
// Log successful response
const duration = Date.now() - startTime;
console.log('[Response]', {
status: response.status,
duration: `${duration}ms`,
timestamp: new Date().toISOString(),
});
// Add custom headers
const modifiedResponse = new Response(response.body, response);
modifiedResponse.headers.set('X-Response-Time', `${duration}ms`);
modifiedResponse.headers.set('X-Powered-By', 'Cloudflare Pages + Next.js');
return modifiedResponse;
} catch (error) {
// Log errors
const duration = Date.now() - startTime;
console.error('[Error]', {
error: error instanceof Error ? error.message : 'Unknown error',
duration: `${duration}ms`,
timestamp: new Date().toISOString(),
});
// Send error to monitoring service
ctx.waitUntil(
fetch('https://monitoring.example.com/errors', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
url: request.url,
error: error instanceof Error ? error.message : 'Unknown error',
timestamp: Date.now(),
}),
})
);
// Return error response
return new Response('Internal Server Error', { status: 500 });
}
},
} as ExportedHandler<{ ASSETS: Fetcher }>;
```
```bash
# Build with custom entrypoint
npx @cloudflare/next-on-pages --custom-entrypoint=./custom-entrypoint.ts
```
--------------------------------
### Report Unsupported Configs in next.config.mjs (ESLint)
Source: https://github.com/cloudflare/next-on-pages/blob/main/packages/eslint-plugin-next-on-pages/docs/rules/no-unsupported-configs.md
This snippet shows how to configure the `next-on-pages/no-unsupported-configs` ESLint rule to report unsupported configuration options in `next.config.mjs`. It demonstrates the basic 'error' level configuration.
```javascript
// eslintrc
"next-on-pages/no-unsupported-configs": "error"
// next.config.mjs
/** @type {import('next').NextConfig} */
const nextConfig = {
compress: true,
~~~~~~~~ // Indicates an unsupported option is flagged here
}
export default nextConfig
```
--------------------------------
### Specify Custom Entrypoint via CLI (Shell)
Source: https://github.com/cloudflare/next-on-pages/blob/main/packages/next-on-pages/docs/advanced-usage.md
Instructs the next-on-pages CLI to use a custom worker entrypoint file. This configuration is applied during the build or deployment process.
```shell
npx @cloudflare/next-on-pages --custom-entrypoint=./custom-entrypoint.ts
```
--------------------------------
### Show Node.js Compatibility Dialog (JavaScript)
Source: https://github.com/cloudflare/next-on-pages/blob/main/packages/next-on-pages/no-nodejs-compat-flag-static-error-page/assets/index.html
This JavaScript snippet demonstrates how to display a modal dialog when a button with the ID 'more-details-btn' is clicked. It utilizes the browser's native dialog element and event listeners. No external libraries are required.
```javascript
const dialog = document.querySelector('dialog');
const moreDetailsBtn = document.querySelector('#more-details-btn');
moreDetailsBtn.addEventListener('click', () => {
dialog.showModal();
});
```
--------------------------------
### Configure ESLint with Next-on-Pages Plugin
Source: https://github.com/cloudflare/next-on-pages/blob/main/packages/eslint-plugin-next-on-pages/README.md
Registers the 'next-on-pages' plugin in your ESLint configuration file (.eslintrc.json). It also shows how to extend the recommended rules and customize specific rules.
```json
// .eslintrc.json
{
"plugins": [
"next-on-pages"
],
"extends": [
"plugin:next-on-pages/recommended"
],
"rules": {
"next-on-pages/no-unsupported-configs": "warn"
}
}
```
--------------------------------
### Valid getStaticPaths with fallback: true and edge runtime
Source: https://github.com/cloudflare/next-on-pages/blob/main/packages/eslint-plugin-next-on-pages/docs/rules/no-pages-nodejs-dynamic-ssg.md
This code snippet represents a valid configuration for `getStaticPaths` when using the 'edge' runtime. `fallback: true` is permitted when the `runtime` is set to `experimental-edge`, enabling dynamic rendering.
```javascript
export async function getStaticPaths() {
return {
paths: // ...
fallback: true
};
}
export const config = {
runtime: 'experimental-edge',
};
// ...
```
--------------------------------
### Valid getStaticPaths fallback: false
Source: https://github.com/cloudflare/next-on-pages/blob/main/packages/eslint-plugin-next-on-pages/docs/rules/no-pages-nodejs-dynamic-ssg.md
This is a valid configuration for `getStaticPaths`. Setting `fallback: false` ensures that only pre-rendered paths are available, avoiding dynamic rendering issues in Node.js environments on Cloudflare Pages.
```javascript
export async function getStaticPaths() {
~~~~~~~~~~~~~~
return {
paths: // ...
fallback: false
};
}
// ...
```
--------------------------------
### Generate a Changeset
Source: https://github.com/cloudflare/next-on-pages/blob/main/docs/contributing.md
This command is used to generate a changeset file for functional changes in the project. It prompts the user to select the type of change (patch, minor, or major) and creates a markdown file in the .changeset directory. This file should be committed and included in pull requests.
```shell
npm run changeset
```
--------------------------------
### Custom Worker Entrypoint Handler (TypeScript)
Source: https://github.com/cloudflare/next-on-pages/blob/main/packages/next-on-pages/docs/advanced-usage.md
Defines a custom worker entrypoint to intercept requests and integrate the next-on-pages fetch handler. This allows for pre- and post-processing of requests and responses.
```typescript
import nextOnPagesHandler from '@cloudflare/next-on-pages/fetch-handler';
export default {
async fetch(request, env, ctx) {
// do something before running the next-on-pages handler
const response = await nextOnPagesHandler.fetch(request, env, ctx);
// do something after running the next-on-pages handler
return response;
},
} as ExportedHandler<{ ASSETS: Fetcher }>;
```
--------------------------------
### Configure ESLint for Next-on-Pages Compatibility
Source: https://context7.com/cloudflare/next-on-pages/llms.txt
This JSON configuration sets up ESLint to enforce compatibility rules for Next.js applications deployed on Cloudflare Pages using the next-on-pages plugin. It extends recommended rules and specifies error/warning levels for specific compatibility checks.
```json
{
"plugins": ["next-on-pages"],
"extends": ["plugin:next-on-pages/recommended"],
"rules": {
"next-on-pages/no-nodejs-runtime": "error",
"next-on-pages/no-unsupported-configs": "warn",
"next-on-pages/no-app-nodejs-dynamic-ssg": "error",
"next-on-pages/no-pages-nodejs-dynamic-ssg": "error"
}
}
```
--------------------------------
### Invalid getStaticPaths fallback: true
Source: https://github.com/cloudflare/next-on-pages/blob/main/packages/eslint-plugin-next-on-pages/docs/rules/no-pages-nodejs-dynamic-ssg.md
This code snippet demonstrates an invalid configuration for `getStaticPaths`. Using `fallback: true` without the 'edge' runtime can lead to issues with dynamic Server-Side Rendering (SSR) in Node.js environments on Cloudflare Pages.
```javascript
export async function getStaticPaths() {
return {
paths: // ...
fallback: true
~~~~
};
}
// ...
```
--------------------------------
### Dynamic Route Rewrite Configuration (JSON)
Source: https://github.com/cloudflare/next-on-pages/blob/main/docs/technical/routing.md
This JSON configuration defines how a dynamic URL path is rewritten to a specific file with query parameters. It uses regular expressions to capture parts of the URL and map them to parameters, which is essential for handling dynamic routes in Next.js applications.
```json
{
"src": "^/blog/(?[^/]+?)(?:/)?$",
"dest": "/blog/[slug]?slug=$slug"
}
```
--------------------------------
### Configure Edge Runtime in Next.js
Source: https://github.com/cloudflare/next-on-pages/blob/main/packages/next-on-pages/README.md
This code snippet shows how to configure a Next.js route to use the Edge Runtime by exporting the `runtime` configuration option. This is essential for server-side code in Next.js applications deployed on Cloudflare Pages.
```typescript
export const runtime = 'edge';
```
--------------------------------
### Invalid generateStaticParams Usage in Next.js
Source: https://github.com/cloudflare/next-on-pages/blob/main/packages/eslint-plugin-next-on-pages/docs/rules/no-app-nodejs-dynamic-ssg.md
This code snippet demonstrates an invalid configuration for `generateStaticParams` in a Next.js application. It lacks the required `dynamicParams` or `runtime` export, which can lead to issues with dynamic server-side rendering on Cloudflare Pages.
```javascript
export async function generateStaticParams() {
// ...
}
// ...
```
--------------------------------
### Access Cloudflare Bindings in Next.js Edge API Route
Source: https://github.com/cloudflare/next-on-pages/blob/main/internal-packages/next-dev/README.md
Demonstrates how to access Cloudflare bindings (like KVNamespace) within a Next.js API route configured for the edge runtime. It uses getRequestContext to retrieve the environment bindings, making them available just as they would be in a production Cloudflare Pages deployment.
```typescript
export const runtime = 'edge';
import { NextRequest } from 'next/server';
import { getRequestContext } from '@cloudflare/next-on-pages';
export async function GET(request: NextRequest) {
const { env } = getRequestContext();
const myKv = env.MY_KV_1;
const valueA = await myKv.get('key-a');
return new Response(`The value of key-a in MY_KV is: ${valueA}`);
}
```
--------------------------------
### Next.js Middleware with Edge Runtime (TypeScript)
Source: https://context7.com/cloudflare/next-on-pages/llms.txt
Implements middleware for authentication, redirects, and request modification in a Next.js application using the edge runtime. It checks for authentication tokens, performs conditional redirects and rewrites, and adds custom headers to responses. The configuration specifies the paths the middleware should apply to.
```typescript
// middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
export function middleware(request: NextRequest) {
const pathname = request.nextUrl.pathname;
// Authentication check
const token = request.cookies.get('auth-token');
if (pathname.startsWith('/dashboard') && !token) {
return NextResponse.redirect(new URL('/login', request.url));
}
// Add custom headers
const response = NextResponse.next();
response.headers.set('X-Custom-Header', 'custom-value');
response.headers.set('X-Pathname', pathname);
// Conditional redirects
if (pathname === '/old-page') {
return NextResponse.redirect(new URL('/new-page', request.url));
}
// Rewrite requests
if (pathname.startsWith('/api/v1')) {
return NextResponse.rewrite(
new URL(pathname.replace('/api/v1', '/api/v2'), request.url)
);
}
return response;
}
export const config = {
matcher: [
'/dashboard/:path*',
'/api/:path*',
'/old-page',
],
};
```
--------------------------------
### Safe Cloudflare Context Access in Next.js (TypeScript)
Source: https://context7.com/cloudflare/next-on-pages/llms.txt
Provides a way to access Cloudflare context safely, returning a fallback value when the context is unavailable, such as during static site generation or prerendering. This prevents errors when platform resources are not present.
```typescript
import { getOptionalRequestContext } from '@cloudflare/next-on-pages';
export const runtime = 'edge';
export default async function UserData() {
const context = getOptionalRequestContext();
let userCount = 0;
if (context) {
// Context available - use bindings
const { env } = context;
const count = await env.MY_KV.get('user:count');
userCount = count ? parseInt(count, 10) : 0;
} else {
// Context not available (e.g., during prerendering)
// Use fallback logic or default values
userCount = -1;
}
return (
Total Users: {userCount}
{userCount === -1 &&
Data unavailable during prerendering
}
);
}
```