@detail-dev/next
v0.0.53
Published
This package implements the Next.js integration for Preflight.
Downloads
13
Readme
This package implements the Next.js integration for Preflight.
Important components:
Runtime Wrapper (
/src/runtime.ts
): Defines the__wrap
function, which is a higher-order function that wraps around Next.js API handlers.The goal is to turn API handlers that look like this:
export default async function (req: NextApiRequest, res: NextApiResponse) { res.status(200).json({ status: "OK" }); }
To this:
export default __wrap(async function ( req: NextApiRequest, res: NextApiResponse ) { res.status(200).json({ status: "OK" }); });
The wrap function does three things:
- Initializes a new span called `ROOT_HTTP_REQUEST_DATA`. This is because we want to create our own root span independent of Next.js's internally generated OTEL spans that we can attach our data to. - Runs the `httpApplyCustomAttributesOnSpan`, `httpRequestHook`, and `httpResponseHook` hooks on the request and response objects. Next.js uses the standard `IncomingMessage` and `OutgoingResponse` APIs in Node.js, so these hooks are **identical** to the ones we run in `HTTPInstrumentation` that is used for Express.js. - Finally, it runs the original API handler function.
Next.js Configuration Enhancer (
/src/with-preflight.ts
): This is what is the starting point for the wrapping to actually happen. ThewithPreflight
function modifies the webpack Next.js configuration (next.config.js
) to target all the API routes and run the wrappingLoader against each of them. Most of this code is borrowed from Sentry (see comment at the top of the file).API Route Transformer (
/src/transform.ts
): This script transforms API route files to wrap the final API route handler export with our__wrap
function. It uses thets-morph
library to parse TypeScript files and modify them by adding the__wrap
function import and applying it to the default export.Webpack Loader (
/src/wrappingLoader.ts
): This custom Webpack loader applies the transformation defined intransform.ts
to API route files during the build process. Basically the glue between Wwebpack and our transform function.Tests (
/src/__tests__
): The test suite includes various fixtures and a test file (transform.test.ts
) to validate the transformation process. The fixtures (/src/__tests__/__fixtures__
) contain sample API route files (input
) and their expected transformed outputs (output
). These tests ensure that the transformation process correctly wraps different types of API route files, preserving their original functionality while enhancing them with the features provided by__wrap
.
Note that the next extension doesn't send PREFLIGHT_VERSION_HEADER
or PREFLIGHT_CLIENT_LIBRARY_HEADER
headers to the backend; both are required now.