Search code examples
typescriptnext.jsgithub-actionsazure-static-web-app

INVALID_URL deploying next.js app to Azure Static Webapp during github actions build


I am getting the error below, and spinning wheels figuring it out. It only happens during my github actions build. When I run the build locally, it works fine and I can hit the route handler. I can also run the github action locally using act and Docker, and then I get the error as well.

Here's the error:

TypeError [ERR_INVALID_URL]: Invalid URL
    at new NodeError (node:internal/errors:405:5)
    at new URL (node:internal/url:676:13)
    at new ni (/home/runner/work/frontend/.next/server/app/api/reports/route.js:6:40210)

And the file in question is src/app/api/reports/route.tsx:

export async function GET(request: Request) {
  const { searchParams } = new URL(request.url);  // <- here is the problem
  const id = searchParams.get('id');
  const partitionKey = searchParams.get('partitionKey');

  if (!id || !partitionKey) {
    return NextResponse.json({msg: 'Success'});
  }

The result I expect is that the build completes and I can hit: http://localhost:3000/api/reports?id=SOME_ID&partitionKey=SOME_KEY

And get a result. The actual result is the error above, during build time (not even runtime).

When I run it locally, the URL above works.

I have tried a ton, including:

  1. I changed the name of the file to route-bad.tsx and the build succeeds
  2. I took out the URL parsing and the build succeeds.
  3. I tried an alternate form of build parsing the just uses strings and the qs library. I still get the error.

Any help is appreciated!


Solution

  • I figured this out. This discussion helped point me in the right direction: https://github.com/vercel/next.js/discussions/35534

    Turns out this was just a red herring:

    const { searchParams } = new URL(request.url); // <- here is the problem

    The real problem is here:

    const cosmosClient = new CosmosClient({
      endpoint: COSMOS_ENDPOINT,
      key: COSMOS_KEY,
    });
    export async function GET(request: Request) {
      ...
    }
    

    Two issues were happening together:

    1. I was creating the CosmosClient outside of the function call, meaning that importing this file caused that bit to be executed. That's why the error happened during the compile. I moved the initialization into the function.
    2. It happened at all because in the github action, the environment variables were not set during the build. They were set later during the deploy. This answer talks about the solution I used to set the environment variables during the build on the github action.

    With those 2 fixed, the error goes away. A tricky one, but I definitely understand React compilation better.