Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Integrate maintenance mode with current middleware #14571

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { get } from "@vercel/edge-config";
import { NextResponse } from "next/server";
import type { NextMiddleware } from "next-api-middleware";

const safeGet = async <T = unknown>(key: string): Promise<T | undefined> => {
try {
Expand All @@ -11,12 +11,13 @@ const safeGet = async <T = unknown>(key: string): Promise<T | undefined> => {

export const config = { matcher: "/:path*" };

export async function middleware() {
export const checkIsInMaintenanceMode: NextMiddleware = async (req, res, next) => {
const isInMaintenanceMode = await safeGet<boolean>("isInMaintenanceMode");
if (!isInMaintenanceMode) return NextResponse.next();
// If is in maintenance mode, return a 503 status code
return NextResponse.json(
{ message: "API is currently under maintenance. Please try again at a later time." },
{ status: 503 }
);
}
if (isInMaintenanceMode) {
return res
.status(503)
.json({ message: "API is currently under maintenance. Please try again at a later time." });
}

await next();
};
3 changes: 3 additions & 0 deletions apps/api/v1/lib/helpers/withMiddleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { label } from "next-api-middleware";

import { addRequestId } from "./addRequestid";
import { captureErrors } from "./captureErrors";
import { checkIsInMaintenanceMode } from "./checkIsInMaintenanceMode";
import { extendRequest } from "./extendRequest";
import {
HTTP_POST,
Expand All @@ -24,6 +25,7 @@ const middleware = {
HTTP_POST,
HTTP_DELETE,
addRequestId,
checkIsInMaintenanceMode,
verifyApiKey,
rateLimitApiKey,
extendRequest,
Expand All @@ -36,6 +38,7 @@ type Middleware = keyof typeof middleware;

const middlewareOrder = [
// The order here, determines the order of execution
"checkIsInMaintenanceMode",
"extendRequest",
"captureErrors",
"verifyApiKey",
Expand Down