Skip to content

lambdaFunctionUrl is undefined #243

@mobob

Description

@mobob

Hey there!

I'm trying to attach an additional behaviour to the cloudfront that is created by NextJS that will route to the existing server function (to route analytics ingest for posthog directly to nextjs).

My initial try was to access lambdaFunctionUrl on the NextJS structure which seems handy, yet it is always null. Searching the code naively too looks like its dangling there and isn't populated (but i'm not really sure how the magic happens).

    const nextJsApp = new Nextjs(this, ...);

    if (!nextJsApp.lambdaFunctionUrl) {
      throw new Error('lambdaFunctionUrl is not available');
    }

    // going down this route didn't help either as it fails with a duplicate construct name...
    // const functionUrl = nextJsApp.serverFunction.lambdaFunction.addFunctionUrl();

    const origin = new origins.FunctionUrlOrigin(nextJsApp.lambdaFunctionUrl, { originId: 'posthog-ingest' });

    const posthogCachePolicy = new cloudfront.CachePolicy(this, 'PosthogCachePolicy', {
      cachePolicyName: `posthog-cors-${props.stageEnv}`,
      headerBehavior: cloudfront.CacheHeaderBehavior.allowList('Origin', 'Authorization'),
      queryStringBehavior: cloudfront.CacheQueryStringBehavior.all(),
      enableAcceptEncodingGzip: true,
      enableAcceptEncodingBrotli: true,
    });

    // Copy any other behavior settings you need
    nextJsApp.distribution.distribution.addBehavior('/ingest', origin, {
      viewerProtocolPolicy: cloudfront.ViewerProtocolPolicy.HTTPS_ONLY,
      allowedMethods: cloudfront.AllowedMethods.ALLOW_ALL,
      cachedMethods: cloudfront.CachedMethods.CACHE_GET_HEAD_OPTIONS,
      cachePolicy: posthogCachePolicy,
      originRequestPolicy: cloudfront.OriginRequestPolicy.CORS_CUSTOM_ORIGIN,
      responseHeadersPolicy: cloudfront.ResponseHeadersPolicy.CORS_ALLOW_ALL_ORIGINS_WITH_PREFLIGHT_AND_SECURITY_HEADERS,
    });

But this fails right off the bat.

Trying to create my own FunctionUrl, to then attach a new origin too, also fails, i'm guessing because i cannot have multiple function urls.

Ultimately if i could access the origin created for the server function that would be ideal, but i'm not sure how to do that either!

Let me know if you have suggestions! Happy to decompose the Nextjs use into its requisite parts to make this easier if thats the suggestion. TIA!!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions