0.0.49 • Published 7 days ago

@detail-dev/next v0.0.49

Weekly downloads
-
License
-
Repository
-
Last release
7 days ago

This package implements the Next.js integration for Preflight.

Important components:

  1. 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.
  2. Next.js Configuration Enhancer (/src/with-preflight.ts): This is what is the starting point for the wrapping to actually happen. The withPreflight 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).

  3. 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 the ts-morph library to parse TypeScript files and modify them by adding the __wrap function import and applying it to the default export.

  4. Webpack Loader (/src/wrappingLoader.ts): This custom Webpack loader applies the transformation defined in transform.ts to API route files during the build process. Basically the glue between Wwebpack and our transform function.

  5. 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.