Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,4 @@ tsconfig.tsbuildinfo
next-env.d.ts
build
.docusaurus
.idea/
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
"eslint-plugin-import": "2.28.1",
"eslint-plugin-n": "16.0.2",
"eslint-plugin-promise": "6.1.1",
"next": "15.4.8",
"next": "16.2.4",
"prettier": "3.0.2",
"typescript": "5.2.2",
"zod": "^4.1.13"
Expand Down
6 changes: 3 additions & 3 deletions packages/next-rest-framework/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "next-rest-framework",
"version": "6.1.1",
"version": "6.1.3",
"description": "Next REST Framework - Type-safe, self-documenting APIs for Next.js",
"keywords": [
"nextjs",
Expand Down Expand Up @@ -39,9 +39,9 @@
"chalk": "4.1.2",
"commander": "10.0.1",
"formidable": "^3.5.1",
"lodash": "4.17.21",
"lodash": "4.18.1",
"prettier": "3.0.2",
"qs": "6.14.1"
"qs": "6.15.1"
},
"devDependencies": {
"@types/formidable": "^3.4.5",
Expand Down
5 changes: 4 additions & 1 deletion packages/next-rest-framework/src/app-router/docs-route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,10 @@ export const docsRoute = (_config?: NextRestFrameworkConfig) => {
}
});
} catch (error) {
logNextRestFrameworkError(error);
logNextRestFrameworkError(error, {
method: _req.method,
url: _req.url
});

return NextResponse.json(
{ message: DEFAULT_ERRORS.unexpectedError },
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,13 @@ import {
import { NextResponse, type NextRequest } from 'next/server';
import { type ZodType, type z } from 'zod';
import { type ValidMethod } from '../constants';
import { type I18NConfig } from 'next/dist/server/config-shared';
import { type NextURL } from 'next/dist/server/web/next-url';
import { type OpenAPIV3_1 } from 'openapi-types';
import { type ResponseCookies } from 'next/dist/compiled/@edge-runtime/cookies';
import { type NextConfig } from 'next';

// Use public API types instead of internal Next.js paths to avoid cross-version type incompatibilities.
type NextURL = NextRequest['nextUrl'];
type ResponseCookies = NextResponse['cookies'];
type I18NConfig = NonNullable<NextConfig['i18n']>;

interface TypedSearchParams<Query = BaseQuery> extends URLSearchParams {
get: <K extends keyof Query & string>(key: K) => string | null;
Expand Down
28 changes: 24 additions & 4 deletions packages/next-rest-framework/src/app-router/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@ import { NextRequest, NextResponse } from 'next/server';
import qs from 'qs';
import { DEFAULT_ERRORS } from '../constants';
import { validateSchema } from '../shared';
import { logNextRestFrameworkError } from '../shared/logging';
import {
logNextRestFrameworkError,
logNextRestFrameworkResponse
} from '../shared/logging';
import { getPathsFromRoute } from '../shared/paths';
import {
type FormDataContentType,
Expand Down Expand Up @@ -30,10 +33,19 @@ export const route = <T extends Record<string, RouteOperationDefinition>>(
_req: NextRequest,
context: { params: Promise<BaseParams> }
) => {
let operationId: string | undefined;

try {
const operation = Object.entries(operations).find(
const operationEntry = Object.entries(operations).find(
([_operationId, operation]) => operation.method === _req.method
)?.[1];
);
operationId = operationEntry?.[0];
const operation = operationEntry?.[1];
const logContext = {
method: _req.method,
operationId,
url: _req.url
};

if (!operation) {
return NextResponse.json(
Expand Down Expand Up @@ -75,6 +87,7 @@ export const route = <T extends Record<string, RouteOperationDefinition>>(
typeof res === 'object';

if (res instanceof Response) {
await logNextRestFrameworkResponse(res, logContext);
return res;
} else if (isOptionsResponse(res)) {
middlewareOptions = res;
Expand All @@ -88,6 +101,7 @@ export const route = <T extends Record<string, RouteOperationDefinition>>(
);

if (res2 instanceof Response) {
await logNextRestFrameworkResponse(res2, logContext);
return res2;
} else if (isOptionsResponse(res2)) {
middlewareOptions = res2;
Expand All @@ -101,6 +115,7 @@ export const route = <T extends Record<string, RouteOperationDefinition>>(
);

if (res3 instanceof Response) {
await logNextRestFrameworkResponse(res3, logContext);
return res3;
} else if (isOptionsResponse(res3)) {
middlewareOptions = res3;
Expand Down Expand Up @@ -295,9 +310,14 @@ export const route = <T extends Record<string, RouteOperationDefinition>>(
);
}

await logNextRestFrameworkResponse(res, logContext);
return res;
} catch (error) {
logNextRestFrameworkError(error);
logNextRestFrameworkError(error, {
method: _req.method,
operationId,
url: _req.url
});
return NextResponse.json(
{ message: DEFAULT_ERRORS.unexpectedError },
{ status: 500 }
Expand Down
11 changes: 9 additions & 2 deletions packages/next-rest-framework/src/app-router/rpc-route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ export const rpcRoute = <
req: NextRequest,
{ params }: { params: Promise<BaseParams> }
) => {
let operationId: string | undefined;

try {
if (req.method !== ValidMethod.POST) {
return NextResponse.json(
Expand All @@ -44,7 +46,8 @@ export const rpcRoute = <
);
}

const operation = operations[(await params).operationId ?? ''];
operationId = (await params).operationId ?? '';
const operation = operations[operationId];

if (!operation) {
return NextResponse.json(
Expand Down Expand Up @@ -221,7 +224,11 @@ export const rpcRoute = <
}
});
} catch (error) {
logNextRestFrameworkError(error);
logNextRestFrameworkError(error, {
method: req.method,
operationId,
url: req.url
});

return NextResponse.json(
{ message: DEFAULT_ERRORS.unexpectedError },
Expand Down
14 changes: 11 additions & 3 deletions packages/next-rest-framework/src/pages-router/api-route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,14 @@ export const apiRoute = <T extends Record<string, ApiRouteOperationDefinition>>(
);
}

let operationId: string | undefined;

try {
const operation = Object.entries(operations).find(
const operationEntry = Object.entries(operations).find(
([_operationId, operation]) => operation.method === req.method
)?.[1];
);
operationId = operationEntry?.[0];
const operation = operationEntry?.[1];

if (!operation) {
res.setHeader(
Expand Down Expand Up @@ -247,7 +251,11 @@ export const apiRoute = <T extends Record<string, ApiRouteOperationDefinition>>(
res.status(501).json({ message: DEFAULT_ERRORS.notImplemented });
}
} catch (error) {
logNextRestFrameworkError(error);
logNextRestFrameworkError(error, {
method: req.method,
operationId,
url: req.url
});
res.status(500).json({ message: DEFAULT_ERRORS.unexpectedError });
}
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,10 @@ export const docsApiRoute = (_config?: NextRestFrameworkConfig) => {
res.setHeader('Content-Type', 'text/html');
res.status(200).send(html);
} catch (error) {
logNextRestFrameworkError(error);
logNextRestFrameworkError(error, {
method: req.method,
url: req.url
});
res.status(500).json({ message: DEFAULT_ERRORS.unexpectedError });
}
};
Expand Down
11 changes: 9 additions & 2 deletions packages/next-rest-framework/src/pages-router/rpc-api-route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,14 +42,17 @@ export const rpcApiRoute = <
);
}

let operationId: string | undefined;

try {
if (req.method !== ValidMethod.POST) {
res.setHeader('Allow', 'POST');
res.status(405).json({ message: DEFAULT_ERRORS.methodNotAllowed });
return;
}

const operation = operations[req.query.operationId?.toString() ?? ''];
operationId = req.query.operationId?.toString() ?? '';
const operation = operations[operationId];

if (!operation) {
res.status(400).json({ message: DEFAULT_ERRORS.operationNotAllowed });
Expand Down Expand Up @@ -202,7 +205,11 @@ export const rpcApiRoute = <
const json = await parseRpcOperationResponseJson(_res);
res.status(200).json(json);
} catch (error) {
logNextRestFrameworkError(error);
logNextRestFrameworkError(error, {
method: req.method,
operationId,
url: req.url
});
res.status(400).json({ message: DEFAULT_ERRORS.unexpectedError });
}
};
Expand Down
96 changes: 94 additions & 2 deletions packages/next-rest-framework/src/shared/logging.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,65 @@
import chalk from 'chalk';

export type NextRestFrameworkErrorLogContext = {
method?: string;
operationId?: string;
route?: string;
url?: string;
};

const formatValue = (value: unknown) => {
if (typeof value === 'string') {
return value;
}

try {
return JSON.stringify(value, null, 2);
} catch {
return String(value);
}
};

const formatError = (error: unknown, depth = 0): string => {
const lines: string[] = [];

if (error instanceof Error) {
lines.push(error.stack ?? `${error.name}: ${error.message}`);

const props = Object.fromEntries(
Object.entries(error).filter(([key]) => key !== 'cause')
);

if (Object.keys(props).length > 0) {
lines.push(`properties: ${formatValue(props)}`);
}

const cause = (error as Error & { cause?: unknown }).cause;
if (cause !== undefined && depth < 3) {
lines.push(`cause:\n${formatError(cause, depth + 1)}`);
}
} else {
lines.push(formatValue(error));
}

return lines.join('\n');
};

const formatContext = (context?: NextRestFrameworkErrorLogContext) => {
if (!context) {
return '';
}

const entries = Object.entries(context).filter(
([, value]) => value !== undefined && value !== ''
);

if (entries.length === 0) {
return '';
}

return `${entries.map(([key, value]) => `${key}: ${value}`).join('\n')}\n`;
};

export const logPagesEdgeRuntimeErrorForRoute = (route: string) => {
console.error(
chalk.red(`---
Expand All @@ -18,10 +78,42 @@ Please use \`docsRoute\` instead: https://vercel.com/docs/functions/edge-functio
);
};

export const logNextRestFrameworkError = (error: unknown) => {
export const logNextRestFrameworkError = (
error: unknown,
context?: NextRestFrameworkErrorLogContext
) => {
console.error(
chalk.red(`Next REST Framework encountered an error:
${error}`)
${formatContext(context)}${formatError(error)}`)
);
};

export const logNextRestFrameworkResponse = async (
response: Response,
context?: NextRestFrameworkErrorLogContext
) => {
if (response.status < 500) {
return;
}

let body: unknown;
try {
const text = await response.clone().text();
if (text) {
try {
body = JSON.parse(text);
} catch {
body = text;
}
}
} catch (error) {
body = `Failed to read response body: ${formatError(error)}`;
}

console.error(
chalk.red(`Next REST Framework returned an error response:
${formatContext(context)}status: ${response.status}
body: ${formatValue(body)}`)
);
};

Expand Down
Loading