### Scheduled Maintenance Configuration Source: https://github.com/r1si/nextjs-maintenance-mode/blob/main/CONTEXT7.md Example JSON configuration for scheduled maintenance with a start and end time. ```json { "enabled": true, "startTime": "2025-01-20T02:00:00Z", "endTime": "2025-01-20T04:00:00Z", "message": "Scheduled maintenance: Database upgrade in progress" } ``` -------------------------------- ### Install Dependencies using npm Source: https://github.com/r1si/nextjs-maintenance-mode/blob/main/example/README.md Installs the necessary project dependencies using the npm package manager. This command is typically run once after cloning a project or before the first build/run. ```bash npm install ``` -------------------------------- ### Extended Maintenance Configuration Source: https://github.com/r1si/nextjs-maintenance-mode/blob/main/CONTEXT7.md Example JSON configuration for extending the maintenance period. ```json { "enabled": true, "startTime": "2025-01-20T02:00:00Z", "endTime": "2025-01-20T06:00:00Z", "message": "Maintenance extended until 6 AM due to complications" } ``` -------------------------------- ### Emergency Maintenance Configuration Source: https://github.com/r1si/nextjs-maintenance-mode/blob/main/CONTEXT7.md Example JSON configuration for immediate, indefinite maintenance. ```json { "enabled": true, "message": "Emergency maintenance in progress. We\'ll be back as soon as possible." } ``` -------------------------------- ### Run Development Server using npm Source: https://github.com/r1si/nextjs-maintenance-mode/blob/main/example/README.md Starts the Next.js development server, allowing for live reloading and immediate feedback during development. Access the application via http://localhost:3000. ```bash npm run dev ``` -------------------------------- ### Early Cancellation Maintenance Configuration Source: https://github.com/r1si/nextjs-maintenance-mode/blob/main/CONTEXT7.md Example JSON configuration for early cancellation of maintenance. ```json { "enabled": false, "startTime": "2025-01-20T02:00:00Z", "endTime": "2025-01-20T04:00:00Z" } ``` -------------------------------- ### Scheduled Maintenance Configuration (JSON) Source: https://github.com/r1si/nextjs-maintenance-mode/blob/main/example/README.md JSON configuration for scheduled maintenance with defined start and end times. The system will automatically enable and disable maintenance mode based on these timestamps. ```json { "enabled": true, "startTime": "2025-01-20T02:00:00Z", "endTime": "2025-01-20T04:00:00Z", "message": "Scheduled maintenance: Database upgrade" } ``` -------------------------------- ### Environment Variable Configuration (Bash) Source: https://github.com/r1si/nextjs-maintenance-mode/blob/main/README.md Example of how to configure maintenance mode using environment variables (legacy approach). ```bash # .env MAINTENANCE_MODE=true ``` -------------------------------- ### Maintenance Mode Configuration (JSON) Source: https://github.com/r1si/nextjs-maintenance-mode/blob/main/README.md Example of the JSON configuration file used to define the maintenance mode settings. ```json { "enabled": true, "endTime": "2025-01-15T12:00:00Z" } ``` -------------------------------- ### Create maintenance configuration file Source: https://github.com/r1si/nextjs-maintenance-mode/blob/main/CONTEXT7.md Define the maintenance mode settings in a JSON file located at public/maintenance.json. Includes enabled status, message, and maintenance window. ```json { "enabled": false, "message": "We are performing scheduled maintenance. We'll be back soon!", "startTime": "", "endTime": "" } ``` -------------------------------- ### Troubleshooting: Incorrect Import - Server Component Source: https://github.com/r1si/nextjs-maintenance-mode/blob/main/CONTEXT7.md Illustrates the correct import statement for server components to configure maintenance options. ```typescript // ❌ WRONG - Don't do this in client components // import { readMaintenanceConfig } from 'nextjs-maintenance-mode/config' ``` -------------------------------- ### Install Next.js Maintenance Mode Source: https://github.com/r1si/nextjs-maintenance-mode/blob/main/README.md Installs the nextjs-maintenance-mode package using npm. This package requires Next.js 16.0.0+, React 18.0.0+, and Node.js 18.0.0+. ```bash npm install nextjs-maintenance-mode ``` -------------------------------- ### File-Based Maintenance Mode Configuration (JSON) Source: https://github.com/r1si/nextjs-maintenance-mode/blob/main/CONTEXT7.md Presents the current, file-based approach for configuring maintenance mode. It involves creating a `maintenance.json` file in the `public` directory with an `enabled` flag. ```json { "enabled": true } ``` -------------------------------- ### Setup proxy for maintenance mode in Next.js 16 Source: https://github.com/r1si/nextjs-maintenance-mode/blob/main/CONTEXT7.md Implement a proxy function to handle maintenance mode redirection. Skips checks for maintenance page, API routes, and static files. Reads configuration from public/maintenance.json. ```typescript import { NextRequest, NextResponse } from 'next/server' import { readMaintenanceConfig, isMaintenanceActive } from 'nextjs-maintenance-mode/config' export function proxy(request: NextRequest) { const pathname = request.nextUrl.pathname // Skip maintenance check for: // - Maintenance page itself // - API routes // - Static files and Next.js internals if ( pathname.startsWith('/maintenance') || pathname.startsWith('/api/') || pathname.startsWith('/_next/') || pathname.includes('.') ) { return NextResponse.next() } // Read maintenance configuration from filesystem const config = readMaintenanceConfig('public/maintenance.json', { silent: true }) // Check if maintenance is active based on time window if (isMaintenanceActive(config)) { return NextResponse.redirect(new URL('/maintenance', request.url)) } return NextResponse.next() } // Optional: Configure matcher for better performance export const config = { matcher: [ '/((?!_next/static|_next/image|favicon.ico).*)', ], } ``` -------------------------------- ### TypeScript Types for Maintenance Config (TypeScript) Source: https://github.com/r1si/nextjs-maintenance-mode/blob/main/CONTEXT7.md Demonstrates how to import and use TypeScript types (`MaintenanceConfig`, `MaintenanceStatus`) from the `nextjs-maintenance-mode` package. This helps in creating type-safe maintenance configurations. ```typescript import type { MaintenanceConfig, MaintenanceStatus } from 'nextjs-maintenance-mode/types' const config: MaintenanceConfig = { enabled: true, message: 'Test' } ``` -------------------------------- ### Troubleshooting: Incorrect Import - Client Component Source: https://github.com/r1si/nextjs-maintenance-mode/blob/main/CONTEXT7.md Illustrates the correct import statement for client components to avoid Node.js module errors. ```typescript // ✅ CORRECT - Use client-only functions import { useMaintenanceStatus } from 'nextjs-maintenance-mode/client' ``` -------------------------------- ### GET /api/maintenance-status Source: https://github.com/r1si/nextjs-maintenance-mode/blob/main/CONTEXT7.md Retrieves the current maintenance status of the application. This endpoint allows clients to check if the application is currently in maintenance mode and get details about the maintenance configuration. ```APIDOC ## GET /api/maintenance-status ### Description Retrieves the current maintenance status of the application, including whether it's active and the configuration details. ### Method GET ### Endpoint /api/maintenance-status ### Parameters #### Query Parameters None #### Request Body None ### Request Example ```json { "example": "No request body needed." } ``` ### Response #### Success Response (200) - **active** (boolean) - Indicates if maintenance mode is currently active. - **config** (object | null) - The maintenance configuration object, or null if an error occurred. - **enabled** (boolean) - Whether maintenance mode is enabled in the config. - **message** (string, optional) - The maintenance message to display. - **startTime** (string, optional) - The start time for scheduled maintenance. - **endTime** (string, optional) - The end time for scheduled maintenance. - **reason** (string) - A description of why maintenance mode is active or inactive, or an error message. #### Response Example ```json { "active": true, "config": { "enabled": true, "message": "We are performing scheduled maintenance. We\'ll be back soon!", "startTime": "", "endTime": "" }, "reason": "Maintenance is enabled in the configuration file." } ``` #### Error Response (500) - **active** (boolean) - `false` - **config** (null) - `null` - **reason** (string) - An error message indicating a problem reading the configuration. #### Error Response Example ```json { "active": false, "config": null, "reason": "Error reading maintenance configuration" } ``` ``` -------------------------------- ### Custom Countdown Display for Maintenance End Time (TypeScript) Source: https://github.com/r1si/nextjs-maintenance-mode/blob/main/CONTEXT7.md Provides an example of using the `useCountdown` hook to display a dynamic countdown to the maintenance end time. It includes logic to only display relevant time units (days, hours, minutes, seconds) based on the remaining time. ```typescript const countdown = useCountdown(endTime) if (countdown) { return (
{countdown.days > 0 && {countdown.days}d } {countdown.hours > 0 && {countdown.hours}h } {countdown.minutes}m {countdown.seconds}s
) } ``` -------------------------------- ### Emergency Maintenance Configuration (JSON) Source: https://github.com/r1si/nextjs-maintenance-mode/blob/main/example/README.md JSON configuration for immediate and indefinite emergency maintenance. 'enabled' is true, and 'endTime' is omitted, meaning maintenance continues until manually disabled. ```json { "enabled": true, "message": "Emergency maintenance in progress." } ``` -------------------------------- ### Scheduled Maintenance with Auto-Start/Stop (JSON) Source: https://github.com/r1si/nextjs-maintenance-mode/blob/main/README.md This JSON configuration sets up a scheduled maintenance window with automatic start and end times. The site will be active before the `startTime` and after the `endTime`, with maintenance active in between. This requires no manual intervention during the window. ```json { "enabled": true, "startTime": "2025-01-20T02:00:00Z", "endTime": "2025-01-20T04:00:00Z", "message": "Scheduled maintenance: Database upgrade in progress" } ``` -------------------------------- ### Enable Maintenance Mode Configuration (JSON) Source: https://github.com/r1si/nextjs-maintenance-mode/blob/main/example/README.md JSON configuration file to enable maintenance mode. Setting 'enabled' to true activates maintenance mode, displaying the provided message and using the specified end time for auto-disable. ```json { "enabled": true, "message": "We are performing scheduled maintenance.", "endTime": "2025-01-15T12:00:00Z" } ``` -------------------------------- ### Build and Development Commands in Bash Source: https://github.com/r1si/nextjs-maintenance-mode/blob/main/CLAUDE.md These npm script commands build the TypeScript library, clean artifacts, and prepare for publishing in the nextjs-maintenance-mode project. They depend on package.json scripts and Node.js/npm environment. Outputs include compiled dist/ files; no specific inputs beyond running in project root. Limitations: Requires Node.js and npm installed. ```bash # Build the library (compiles TypeScript to dist/) npm run build # Clean build artifacts npm run clean # Prepare for publishing (runs build automatically) npm run prepublishOnly ``` -------------------------------- ### Create API route for maintenance status Source: https://github.com/r1si/nextjs-maintenance-mode/blob/main/CONTEXT7.md Implement an API endpoint to check maintenance status. Returns the current maintenance configuration and status, with error handling for configuration read failures. ```typescript import { NextResponse } from 'next/server' import { getMaintenanceStatus } from 'nextjs-maintenance-mode/config' export async function GET() { try { // Get complete status with reason const status = getMaintenanceStatus('public/maintenance.json') return NextResponse.json(status) } catch (error) { console.error('Error fetching maintenance status:', error) // Return safe default on error return NextResponse.json( { active: false, config: null, reason: 'Error reading maintenance configuration', }, { status: 500 } ) } } ``` -------------------------------- ### Maintenance Behavior Flow (Pseudocode) Source: https://github.com/r1si/nextjs-maintenance-mode/blob/main/README.md This pseudocode illustrates the logic flow for determining the maintenance status. It starts by checking the `enabled` flag, then considers `startTime` and `endTime` if `enabled` is true, ultimately deciding whether to allow access or redirect to a maintenance page. ```plaintext Request arrives ↓ Read maintenance.json ↓ enabled = false? → YES → Maintenance OFF (allow access) ↓ NO startTime exists? → YES → now < startTime? → YES → Maintenance OFF ↓ NO ↓ NO endTime exists? → YES → now > endTime? → YES → Maintenance OFF ↓ NO ↓ NO Maintenance ON (redirect to /maintenance) ``` -------------------------------- ### API Route for Maintenance Status Checks (TypeScript) Source: https://context7.com/r1si/nextjs-maintenance-mode/llms.txt This API route creates an endpoint to fetch and return the current maintenance status in JSON format for client-side polling. It uses the nextjs-maintenance-mode config to get status from a JSON file and handles errors gracefully. The GET function has no inputs and outputs a JSON object with status details; limitations include dependency on file system access and potential errors if the config file is inaccessible. ```typescript // app/api/maintenance-status/route.ts import { NextResponse } from 'next/server'; import { getMaintenanceStatus } from 'nextjs-maintenance-mode/config'; export async function GET() { try { const status = getMaintenanceStatus('public/maintenance.json'); return NextResponse.json(status); } catch (error) { console.error('Error fetching maintenance status:', error); return NextResponse.json( { active: false, config: null, reason: 'Error reading maintenance configuration', }, { status: 500 } ); } } // Example response when active: // { // "active": true, // "config": { // "enabled": true, // "endTime": "2025-01-15T12:00:00Z", // "message": "System upgrade in progress" // }, // "reason": "Maintenance active until 2025-01-15T12:00:00Z" // } ``` -------------------------------- ### Maintenance Configuration File Format (JSON) Source: https://context7.com/r1si/nextjs-maintenance-mode/llms.txt Defines the structure of the JSON configuration file used to control maintenance mode behavior, including options for enabling/disabling, setting start/end times, and providing custom messages. The examples illustrate valid and invalid configurations. ```json // public/maintenance.json // Example 1: Maintenance disabled (safe default) { "enabled": false } // Example 2: Immediate maintenance mode (no time constraints) { "enabled": true, "message": "Emergency database maintenance in progress" } // Example 3: Scheduled maintenance with time window { "enabled": true, "startTime": "2025-01-15T10:00:00Z", "endTime": "2025-01-15T12:00:00Z", "message": "Scheduled system upgrade" } // Example 4: Maintenance with start time only (manual end) { "enabled": true, "startTime": "2025-01-15T10:00:00Z", "message": "Maintenance begins at 10 AM UTC" } // Example 5: Invalid config (treated as disabled) { "enabled": "yes", // Must be boolean "invalid": true } // Returns: { enabled: false } ``` -------------------------------- ### File-Based Maintenance Mode Check (TypeScript) Source: https://github.com/r1si/nextjs-maintenance-mode/blob/main/CONTEXT7.md Illustrates the TypeScript code used with the file-based maintenance mode. It reads the `maintenance.json` file and uses `isMaintenanceActive` to determine the current maintenance status. ```typescript const config = readMaintenanceConfig('public/maintenance.json') const isActive = isMaintenanceActive(config) ``` -------------------------------- ### Next.js Maintenance Proxy Logic (TypeScript) Source: https://github.com/r1si/nextjs-maintenance-mode/blob/main/example/README.md TypeScript code for Next.js 16 proxy (formerly middleware) that intercepts requests. It reads the maintenance configuration and redirects users to the maintenance page if enabled. ```typescript import { NextRequest, NextResponse } from 'next/server'; import fs from 'fs/promises'; import path from 'path'; const MAINTENANCE_CONFIG_PATH = path.join(process.cwd(), 'public', 'maintenance.json'); async function getMaintenanceConfig() { try { const data = await fs.readFile(MAINTENANCE_CONFIG_PATH, 'utf-8'); const config = JSON.parse(data); const now = new Date(); if (config.startTime && new Date(config.startTime) > now) { return { ...config, enabled: false }; // Maintenance not started yet } if (config.endTime && new Date(config.endTime) < now) { return { ...config, enabled: false }; // Maintenance has ended } return config; } catch (error) { console.error('Error reading maintenance config:', error); return { enabled: false, message: 'Error checking status' }; } } export async function GET(request: NextRequest) { const config = await getMaintenanceConfig(); const isMaintenancePage = request.nextUrl.pathname.startsWith('/maintenance'); if (config.enabled && !isMaintenancePage) { const maintenanceUrl = new URL('/maintenance', request.url); maintenanceUrl.searchParams.set('message', config.message || 'Maintenance in progress'); maintenanceUrl.searchParams.set('endTime', config.endTime || ''); return NextResponse.redirect(maintenanceUrl); } if (!config.enabled && isMaintenancePage) { // If maintenance is disabled and user is on maintenance page, redirect to home return NextResponse.redirect(new URL('/', request.url)); } // For Next.js 16, use NextResponse.rewrite or pass control to Next.js if not handling // For older versions or different setups, you might return NextResponse.next() // This example assumes basic proxy behavior; adjust as needed for specific Next.js versions. // If you are not returning a response here, Next.js will handle the request normally. // For demonstration, let's assume we always want to process or pass through. // If no redirect happens, let Next.js handle the request. return NextResponse.next(); } // Add POST, PUT, DELETE etc. if your proxy needs to handle other methods // export async function POST(request: NextRequest) { /* ... */ } ``` -------------------------------- ### Disable Maintenance Mode Configuration (JSON) Source: https://github.com/r1si/nextjs-maintenance-mode/blob/main/example/README.md JSON configuration file to disable maintenance mode. Setting 'enabled' to false reverts the application to normal operation. Changes are typically reflected after a refresh. ```json { "enabled": false } ``` -------------------------------- ### Environment Variable Maintenance Mode Check (TypeScript) Source: https://github.com/r1si/nextjs-maintenance-mode/blob/main/CONTEXT7.md Shows the corresponding TypeScript code to check for the presence and value of the `MAINTENANCE_MODE` environment variable, which was used in the older approach to control maintenance status. ```typescript const isMaintenanceMode = process.env.MAINTENANCE_MODE === 'true' ``` -------------------------------- ### Debugging Maintenance Config in Proxy (TypeScript) Source: https://github.com/r1si/nextjs-maintenance-mode/blob/main/CONTEXT7.md Adds logging to `proxy.ts` to help debug issues with reading and interpreting the maintenance configuration. It helps verify that the `maintenance.json` file is being read correctly and that the maintenance status is accurately determined. ```typescript const config = readMaintenanceConfig('public/maintenance.json', { silent: false }) console.log('Maintenance config:', config) console.log('Is active:', isMaintenanceActive(config)) ``` -------------------------------- ### Get Maintenance Status (TypeScript) Source: https://github.com/r1si/nextjs-maintenance-mode/blob/main/README.md This function retrieves the complete maintenance status, including the reason for maintenance. ```typescript const status = getMaintenanceStatus(); // { active: true, config: {...}, reason: "Maintenance active until..." } ``` -------------------------------- ### Maintenance JSON Configuration with UTC Timestamps (JSON) Source: https://github.com/r1si/nextjs-maintenance-mode/blob/main/CONTEXT7.md Defines the structure for `maintenance.json` when using scheduled maintenance windows. It emphasizes the use of UTC timestamps in ISO 8601 format (indicated by 'Z') for `startTime` and `endTime` to avoid time zone discrepancies. ```json { "enabled": true, "startTime": "2025-01-20T02:00:00Z", // ← The "Z" means UTC "endTime": "2025-01-20T04:00:00Z" } ``` -------------------------------- ### Convert Local Time to UTC (JavaScript) Source: https://github.com/r1si/nextjs-maintenance-mode/blob/main/CONTEXT7.md Provides a JavaScript utility to convert a local date and time string into its ISO 8601 UTC representation. This is useful for ensuring consistency when setting maintenance schedule times. ```javascript const localDate = new Date('2025-01-20 02:00:00') const utcString = localDate.toISOString() console.log(utcString) // "2025-01-20T02:00:00.000Z" ``` -------------------------------- ### Next.js Maintenance Page Component (TypeScript) Source: https://github.com/r1si/nextjs-maintenance-mode/blob/main/example/README.md React component for the maintenance page in a Next.js App Router application. It displays a message and a countdown timer, polling the status API periodically. ```typescript import React, { useState, useEffect } from 'react'; import { useSearchParams } from 'next/navigation'; const MaintenancePage = () => { const searchParams = useSearchParams(); const initialMessage = searchParams.get('message') || 'Maintenance in progress'; const initialEndTime = searchParams.get('endTime'); const [message, setMessage] = useState(initialMessage); const [timeLeft, setTimeLeft] = useState(null); const [isLoading, setIsLoading] = useState(false); const calculateTimeLeft = (endTimeString?: string | null) => { if (!endTimeString) return null; const endTime = new Date(endTimeString).getTime(); const now = new Date().getTime(); const difference = endTime - now; if (difference <= 0) { return 0; } return Math.round(difference / 1000); // Time in seconds }; useEffect(() => { setTimeLeft(calculateTimeLeft(initialEndTime)); const timer = setInterval(() => { setTimeLeft(calculateTimeLeft(initialEndTime)); }, 1000); // Poll status API every 30 seconds const statusPoll = setInterval(async () => { if (isLoading) return; // Prevent concurrent polls setIsLoading(true); try { const res = await fetch('/api/maintenance-status'); if (!res.ok) throw new Error('Failed to fetch status'); const data = await res.json(); setMessage(data.message || 'Maintenance in progress'); if (!data.enabled || (data.endTime && new Date(data.endTime) < new Date())) { window.location.reload(); // Redirect if maintenance ends } else if (data.endTime) { setTimeLeft(calculateTimeLeft(data.endTime)); } } catch (error) { console.error('Error polling maintenance status:', error); } finally { setIsLoading(false); } }, 30000); return () => { clearInterval(timer); clearInterval(statusPoll); }; }, [initialEndTime, initialMessage]); const formatTime = (seconds: number | null) => { if (seconds === null || seconds === undefined) return '...'; if (seconds === 0) return 'Maintenance ended!'; const days = Math.floor(seconds / (3600 * 24)); const hours = Math.floor((seconds % (3600 * 24)) / 3600); const minutes = Math.floor((seconds % 3600) / 60); const remainingSeconds = seconds % 60; let timeString = ''; if (days > 0) timeString += `${days}d `; if (hours > 0) timeString += `${hours}h `; if (minutes > 0) timeString += `${minutes}m `; timeString += `${remainingSeconds}s`; return timeString.trim(); }; return (

Under Maintenance

{message}

{timeLeft !== null && timeLeft > 0 && (

Estimated time remaining:

{formatTime(timeLeft)}

)} {timeLeft === 0 &&

The maintenance is now complete. Please refresh the page.

}
); }; export default MaintenancePage; ``` -------------------------------- ### Validate Maintenance Config (TypeScript) Source: https://context7.com/r1si/nextjs-maintenance-mode/llms.txt Demonstrates the `validateMaintenanceConfig` type guard function to ensure the configuration object conforms to the expected structure and data types. It shows examples of both valid and invalid configurations and their corresponding validation results. ```typescript import { validateMaintenanceConfig } from 'nextjs-maintenance-mode/config'; // Valid configuration const validConfig = { enabled: true, startTime: "2025-01-15T10:00:00Z", endTime: "2025-01-15T12:00:00Z", message: "Maintenance" }; console.log(validateMaintenanceConfig(validConfig)); // true // Invalid: enabled is not boolean const invalid1 = { enabled: "true" }; console.log(validateMaintenanceConfig(invalid1)); // false // Invalid: startTime is not string const invalid2 = { enabled: true, startTime: 12345 }; console.log(validateMaintenanceConfig(invalid2)); // false // Valid: minimal config const minimal = { enabled: false }; console.log(validateMaintenanceConfig(minimal)); // true // Invalid: not an object console.log(validateMaintenanceConfig(null)); // false console.log(validateMaintenanceConfig("string")); // false ``` -------------------------------- ### API: GET /api/maintenance-status Source: https://github.com/r1si/nextjs-maintenance-mode/blob/main/README.md Fetches the current maintenance status from the server. This endpoint is typically polled by client components to check if maintenance is active. ```APIDOC ## GET /api/maintenance-status ### Description Retrieves the current maintenance status, including whether maintenance is active and any associated configuration details. ### Method GET ### Endpoint /api/maintenance-status ### Parameters None ### Request Example None ### Response #### Success Response (200) - **active** (boolean) - Indicates if maintenance mode is currently active. - **config** (object) - The maintenance configuration object, which may include details like `startTime`, `endTime`, and `reason`. - **reason** (string) - A message explaining the reason for the maintenance, if applicable. #### Response Example ```json { "active": true, "config": { "enabled": true, "endTime": "2025-01-15T12:00:00Z", "reason": "Scheduled maintenance" }, "reason": "Maintenance active until 2025-01-15T12:00:00Z" } ``` ``` -------------------------------- ### Custom Polling Interval for Maintenance Status (TypeScript) Source: https://github.com/r1si/nextjs-maintenance-mode/blob/main/CONTEXT7.md Shows how to configure the `useMaintenanceStatus` hook to poll for maintenance status updates at a custom interval. This allows for more frequent or less frequent checks than the default. ```typescript const { status } = useMaintenanceStatus({ pollInterval: 10000, // Poll every 10 seconds instead of 30 autoPoll: true, }) ``` -------------------------------- ### Next.js Maintenance Page Component Source: https://github.com/r1si/nextjs-maintenance-mode/blob/main/CONTEXT7.md This component displays the maintenance page, handling loading states, errors, and displaying a countdown timer if provided. It utilizes hooks from the nextjs-maintenance-mode/client library for fetching maintenance status and managing the countdown. ```typescript import {"use client" as default} from 'next/navigation' import { useMaintenanceStatus, useCountdown, formatCountdown } from 'nextjs-maintenance-mode/client' import { useRouter } from 'next/navigation' import { useEffect } from 'react' export default function MaintenancePage() { const router = useRouter() // Fetch status and auto-poll every 30 seconds const { status, isLoading, error, refetch } = useMaintenanceStatus({ pollInterval: 30000, autoPoll: true, }) // Live countdown to endTime (updates every second) const countdown = useCountdown(status?.config?.endTime) // Format countdown as human-readable string const timeRemaining = formatCountdown(countdown) // Auto-redirect when maintenance is no longer active useEffect(() => { if (status && !status.active) { console.log('Maintenance ended, redirecting to homepage...') router.push('/') } }, [status, router]) if (isLoading) { return (

Loading...

) } if (error) { return (

Error

Unable to fetch maintenance status

) } return (

🛠️ Under Maintenance

{status?.config?.message || 'We are performing scheduled maintenance. We'll be back soon!'}

{timeRemaining && (

Estimated completion in:

{timeRemaining}

)}

This page will automatically refresh when maintenance is complete.

) } ``` -------------------------------- ### Get comprehensive maintenance status Source: https://context7.com/r1si/nextjs-maintenance-mode/llms.txt Returns detailed maintenance status including active state, full config, and human-readable reason. Use the default path or supply a custom file path to inspect current configuration and compute human-readable explanations. ```TypeScript import { getMaintenanceStatus } from 'nextjs-maintenance-mode/config'; const status = getMaintenanceStatus(); const status2 = getMaintenanceStatus('public/maintenance.json'); const status3 = getMaintenanceStatus(); ``` -------------------------------- ### Skip Maintenance Redirect for Maintenance Page (TypeScript) Source: https://github.com/r1si/nextjs-maintenance-mode/blob/main/CONTEXT7.md A code snippet for `proxy.ts` that prevents the maintenance redirect logic from interfering with the actual maintenance page. It ensures that requests to `/maintenance` are allowed to proceed without redirection. ```typescript if (pathname.startsWith('/maintenance')) { return NextResponse.next() // ← Don't redirect maintenance page } ``` -------------------------------- ### Next.js Maintenance Status API Route (TypeScript) Source: https://github.com/r1si/nextjs-maintenance-mode/blob/main/example/README.md API route in Next.js for polling the maintenance status. This endpoint can be used by the frontend to check if maintenance is active without a full page reload. ```typescript import { NextResponse } from 'next/server'; import fs from 'fs/promises'; import path from 'path'; export async function GET() { try { const filePath = path.join(process.cwd(), 'public', 'maintenance.json'); const data = await fs.readFile(filePath, 'utf-8'); const config = JSON.parse(data); return NextResponse.json(config); } catch (error) { console.error('Error reading maintenance.json:', error); return NextResponse.json({ enabled: false, message: 'Error checking status' }, { status: 500 }); } } ``` -------------------------------- ### GET /api/maintenance-status Source: https://context7.com/r1si/nextjs-maintenance-mode/llms.txt This API endpoint retrieves the current maintenance status from the configuration file. It allows client-side applications to poll for updates on maintenance activity. The endpoint returns whether maintenance is active, the configuration details, and a reason if applicable. ```APIDOC ## GET /api/maintenance-status ### Description Retrieves the current maintenance status, including whether it's active, the configuration, and any associated message or end time. Used for client-side polling to handle dynamic maintenance updates. ### Method GET ### Endpoint /api/maintenance-status ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example N/A (GET request with no body) ### Response #### Success Response (200) - **active** (boolean) - Indicates if maintenance is currently active. - **config** (object) - Maintenance configuration details, including enabled status, endTime, and message. - **reason** (string) - Explanation of the maintenance status, such as end time if active. #### Response Example { "active": true, "config": { "enabled": true, "endTime": "2025-01-15T12:00:00Z", "message": "System upgrade in progress" }, "reason": "Maintenance active until 2025-01-15T12:00:00Z" } #### Error Response (500) - **active** (boolean) - Set to false on error. - **config** (null) - Null on error. - **reason** (string) - Error message, e.g., 'Error reading maintenance configuration'. #### Error Response Example { "active": false, "config": null, "reason": "Error reading maintenance configuration" } ``` -------------------------------- ### Manual Refetch of Maintenance Status (TypeScript) Source: https://github.com/r1si/nextjs-maintenance-mode/blob/main/CONTEXT7.md Illustrates how to disable automatic polling for maintenance status and manually trigger a status refresh using the `refetch` function returned by `useMaintenanceStatus`. This is useful for updating status on user interaction, like clicking a button. ```typescript const { status, refetch } = useMaintenanceStatus({ autoPoll: false, // Disable auto-polling }) // Manually trigger refresh ``` -------------------------------- ### Prepare Future Maintenance Without Activating (JSON) Source: https://github.com/r1si/nextjs-maintenance-mode/blob/main/README.md This configuration prepares a future maintenance schedule but keeps the site active by setting `enabled` to `false`. The maintenance will not auto-start at the `startTime` unless `enabled` is changed to `true` beforehand. This allows for pre-configuration without disrupting current users. ```json { "enabled": false, "startTime": "2025-01-20T02:00:00Z", "endTime": "2025-01-20T04:00:00Z", "message": "Scheduled maintenance" } ``` -------------------------------- ### Check maintenance window using TypeScript Source: https://context7.com/r1si/nextjs-maintenance-mode/llms.txt Demonstrates how to import and call isInMaintenanceWindow with various configurations. Shows handling of no constraints, before/within/after windows, and invalid date formats. Returns a boolean indicating maintenance status. ```typescript import { isInMaintenanceWindow } from 'nextjs-maintenance-mode/config'; // No time constraints (always within window) const config1 = { enabled: true }; console.log(isInMaintenanceWindow(config1)); // true // Before start time (outside window) const config2 = { enabled: true, startTime: "2025-12-25T00:00:00Z", endTime: "2025-12-25T06:00:00Z" }; console.log(isInMaintenanceWindow(config2)); // false (if before Dec 25) // Within time window const config3 = { enabled: true, startTime: "2025-01-01T00:00:00Z", endTime: "2025-12-31T23:59:59Z" }; console.log(isInMaintenanceWindow(config3)); // true (if in 2025) // After end time (outside window) const config4 = { enabled: true, startTime: "2020-01-01T00:00:00Z", endTime: "2020-12-31T23:59:59Z" }; console.log(isInMaintenanceWindow(config4)); // false // Invalid date format (ignored, treated as no constraint) const config5 = { enabled: true, startTime: "invalid-date" }; console.log(isInMaintenanceWindow(config5)); // true (logs warning) ``` -------------------------------- ### Package.json Exports Configuration in JSON Source: https://github.com/r1si/nextjs-maintenance-mode/blob/main/CLAUDE.md Defines conditional exports for module separation in the npm package, mapping subpaths to specific dist files for server/client code. Used by Node.js and bundlers like Next.js for proper imports. No runtime dependencies; inputs are package resolution requests. Limitations: Comments are non-standard JSON but serve as documentation. ```json { ".": "./dist/index.js", // Main entry "./config": "./dist/config.js", // Server-side only "./client": "./dist/client.js", // Client-side only "./types": "./dist/types.js" // Shared types } ``` -------------------------------- ### Implement NextJS Maintenance Page (TypeScript) Source: https://context7.com/r1si/nextjs-maintenance-mode/llms.txt Demonstrates a complete maintenance page implementation using `nextjs-maintenance-mode/client` hooks for status, countdown, and auto-redirect. The page displays a message, countdown timer, and automatically redirects when maintenance ends. ```typescript 'use client'; import { useMaintenanceStatus, useCountdown, formatCountdown } from 'nextjs-maintenance-mode/client'; import { useRouter } from 'next/navigation'; import { useEffect } from 'react'; export default function MaintenancePage() { const router = useRouter(); const { status, isLoading } = useMaintenanceStatus({ pollInterval: 30000 }); const countdown = useCountdown(status?.config?.endTime); const timeRemaining = formatCountdown(countdown); // Auto-redirect when maintenance ends useEffect(() => { if (status && !status.active) { router.push('/'); } }, [status, router]); if (isLoading) { return ; } return (

Under Maintenance

{status?.config?.message || 'We are performing scheduled maintenance.'}

{timeRemaining && (

Estimated completion in:

{timeRemaining}

)}

This page will automatically refresh when maintenance is complete.

); } ``` -------------------------------- ### Client-Side Hooks Source: https://github.com/r1si/nextjs-maintenance-mode/blob/main/README.md Hooks for client components to interact with maintenance status, manage countdowns, and format time. ```APIDOC ## Client-Side Hooks ### `useMaintenanceStatus(options?)` #### Description A React hook that fetches the maintenance status from the `/api/maintenance-status` endpoint and automatically polls it at a specified interval. It provides the status, loading state, and any errors. #### Method React Hook #### Parameters - **options** (object) - Optional. Configuration options for polling. - **pollInterval** (number) - Optional. The interval in milliseconds to poll the API. Defaults to 30000 (30 seconds). - **autoPoll** (boolean) - Optional. If true, polling is automatically started. Defaults to true. #### Request Example ```typescript import { useMaintenanceStatus } from "@/lib/maintenance/client"; const { status, isLoading, error, refetch } = useMaintenanceStatus({ pollInterval: 30000, autoPoll: true }); ``` ### `useCountdown(endTime?)` #### Description A React hook that takes an end time and provides a live countdown object that updates every second. It calculates the remaining days, hours, minutes, and seconds. #### Method React Hook #### Parameters - **endTime** (string | Date | null) - Optional. The target end time for the countdown. Can be an ISO 8601 string or a Date object. If null or undefined, the countdown will not run. #### Request Example ```typescript import { useCountdown } from "@/lib/maintenance/client"; const countdown = useCountdown("2025-01-15T12:00:00Z"); // countdown object: { days, hours, minutes, seconds, totalSeconds } ``` ### `formatCountdown(countdown)` #### Description Formats a countdown object (typically generated by `useCountdown`) into a human-readable string, such as "2h 30m" or "45m 30s". #### Method Function #### Parameters - **countdown** (object) - The countdown object with properties like `days`, `hours`, `minutes`, `seconds`. #### Request Example ```typescript import { formatCountdown } from "@/lib/maintenance/client"; const formattedTime = formatCountdown({ days: 0, hours: 2, minutes: 30, seconds: 45, totalSeconds: 9345 }); // formattedTime will be "2h 30m" ``` ``` -------------------------------- ### Create Maintenance Configuration Source: https://github.com/r1si/nextjs-maintenance-mode/blob/main/README.md Defines the maintenance mode settings in a JSON file. This file controls whether maintenance is active, the message displayed, and optional start/end times for scheduled maintenance windows. ```json { "enabled": false, "message": "We are performing scheduled maintenance. We'll be back soon!" } ``` ```json { "enabled": true, "startTime": "2025-01-15T10:00:00Z", "endTime": "2025-01-15T12:00:00Z", "message": "We are performing scheduled maintenance. We'll be back soon!" } ``` -------------------------------- ### Server-Side Proxy Logic (TypeScript) Source: https://github.com/r1si/nextjs-maintenance-mode/blob/main/README.md This code snippet demonstrates the server-side proxy logic in `proxy.ts`. It checks for maintenance status based on a configuration file and redirects users to the maintenance page if maintenance is active. ```typescript // ✅ CORRECT - Import from /config for server-side import { readMaintenanceConfig, isMaintenanceActive } from "@/lib/maintenance/config"; // In proxy.ts export function proxy(request: NextRequest) { const pathname = request.nextUrl.pathname; // Skip maintenance check for maintenance page and APIs if (!pathname.startsWith("/maintenance") && !pathname.startsWith("/api/")) { const config = readMaintenanceConfig("public/maintenance.json", { silent: true }); if (isMaintenanceActive(config)) { return NextResponse.redirect(new URL("/maintenance", request.url)); } } return NextResponse.next(); } ``` -------------------------------- ### Server-Side Functions Source: https://github.com/r1si/nextjs-maintenance-mode/blob/main/README.md Functions for server-side logic, including reading configuration and checking maintenance status within API routes or server components. ```APIDOC ## Server-Side Functions ### `readMaintenanceConfig(filePath?, options?)` #### Description Reads and validates the maintenance configuration from a specified file path. It's crucial to import this from `@/lib/maintenance/config` on the server-side. #### Method Function Call #### Parameters - **filePath** (string) - Optional. The path to the maintenance JSON file. Defaults to `public/maintenance.json`. - **options** (object) - Optional. Configuration options. - **silent** (boolean) - Optional. If true, errors during reading will not be logged. #### Request Example ```typescript import { readMaintenanceConfig } from "@/lib/maintenance/config"; const config = readMaintenanceConfig("public/maintenance.json", { silent: true }); ``` ### `isMaintenanceActive(config)` #### Description Checks if maintenance is currently active based on the provided configuration object. This function should be used after reading the configuration. #### Method Function Call #### Parameters - **config** (object) - The maintenance configuration object, typically obtained from `readMaintenanceConfig`. #### Request Example ```typescript import { readMaintenanceConfig, isMaintenanceActive } from "@/lib/maintenance/config"; const config = readMaintenanceConfig(); if (isMaintenanceActive(config)) { // Maintenance is active } ``` ### `getMaintenanceStatus(filePath?)` #### Description Gets the complete maintenance status, including the configuration and a human-readable reason. Useful for debugging or providing detailed status information. #### Method Function Call #### Parameters - **filePath** (string) - Optional. The path to the maintenance JSON file. Defaults to `public/maintenance.json`. #### Request Example ```typescript import { getMaintenanceStatus } from "@/lib/maintenance/config"; const status = getMaintenanceStatus(); // status might look like: { active: true, config: {...}, reason: "Maintenance active until..." } ``` ``` -------------------------------- ### Use Countdown Hook (TypeScript) Source: https://github.com/r1si/nextjs-maintenance-mode/blob/main/README.md A client-side hook providing a live countdown to the maintenance end time. ```typescript const countdown = useCountdown("2025-01-15T12:00:00Z"); // { days, hours, minutes, seconds, totalSeconds } ``` -------------------------------- ### Disable Maintenance Configuration (JSON) Source: https://github.com/r1si/nextjs-maintenance-mode/blob/main/README.md This is the standard configuration for disabling maintenance mode and ensuring the site is fully accessible. Setting `enabled` to `false` guarantees that no maintenance is active, regardless of any `startTime` or `endTime` values present in the file. ```json { "enabled": false } ``` -------------------------------- ### Set Up Maintenance Proxy in Next.js Source: https://github.com/r1si/nextjs-maintenance-mode/blob/main/README.md Implements a proxy middleware in Next.js to intercept requests and redirect users to a maintenance page when maintenance mode is active. It skips checks for the maintenance page itself, API routes, and Next.js internal paths. ```typescript import { NextRequest, NextResponse } from 'next/server' import { readMaintenanceConfig, isMaintenanceActive } from 'nextjs-maintenance-mode/config' export function proxy(request: NextRequest) { const pathname = request.nextUrl.pathname // Skip maintenance check for maintenance page, API routes, and static files if ( pathname.startsWith('/maintenance') || pathname.startsWith('/api/') || pathname.startsWith('/_next/') ) { return NextResponse.next() } // Check if maintenance is active const config = readMaintenanceConfig('public/maintenance.json', { silent: true }) if (isMaintenanceActive(config)) { return NextResponse.redirect(new URL('/maintenance', request.url)) } return NextResponse.next() } ``` -------------------------------- ### Immediate Indefinite Maintenance Configuration (JSON) Source: https://github.com/r1si/nextjs-maintenance-mode/blob/main/README.md This JSON configuration enables maintenance mode immediately and indefinitely. It's useful for emergency situations where there's no set end time. Simply set `enabled` to `false` to disable it. ```json { "enabled": true, "message": "Emergency maintenance in progress. We'll be back as soon as possible." } ``` -------------------------------- ### Create Maintenance Page Component Source: https://github.com/r1si/nextjs-maintenance-mode/blob/main/README.md A client-side React component for the maintenance page. It fetches the maintenance status, displays the custom message, and shows a countdown to the end of the maintenance period. It also handles auto-redirection back to the homepage when maintenance ends. ```typescript 'use client' import { useMaintenanceStatus, useCountdown, formatCountdown } from 'nextjs-maintenance-mode/client' import { useRouter } from 'next/navigation' import { useEffect } from 'react' export default function MaintenancePage() { const router = useRouter() const { status, isLoading } = useMaintenanceStatus() const countdown = useCountdown(status?.config?.endTime) const timeRemaining = formatCountdown(countdown) // Auto-redirect when maintenance ends useEffect(() => { if (status && !status.active) { router.push('/') } }, [status, router]) return (

Under Maintenance

{status?.config?.message}

{timeRemaining &&

Back in: {timeRemaining}

}
) } ```