convex-backend icon indicating copy to clipboard operation
convex-backend copied to clipboard

Next.js SDK bad URL defaulting

Open xixixao opened this issue 11 months ago • 2 comments

The way backend url option is defaulted is error-prone.

Right now:

function setupClient(options: NextjsOptions) {
  const client = new ConvexHttpClient(
    getConvexUrl(options.url, options.skipConvexDeploymentUrlCheck ?? false),
  );
  if (options.token !== undefined) {
    client.setAuth(options.token);
  }
  if (options.adminToken !== undefined) {
    client.setAdminAuth(options.adminToken);
  }
  client.setFetchOptions({ cache: "no-store" });
  return client;
}


function getConvexUrl(
  deploymentUrl: string | undefined,
  skipConvexDeploymentUrlCheck: boolean,
) {
  const url = deploymentUrl ?? process.env.NEXT_PUBLIC_CONVEX_URL;
  const isFromEnv = deploymentUrl === undefined;
  if (typeof url !== "string") {
    throw new Error(
      isFromEnv
        ? `Environment variable NEXT_PUBLIC_CONVEX_URL is not set.`
        : `Convex function called with invalid deployment address.`,
    );
  }
  if (!skipConvexDeploymentUrlCheck) {
    validateDeploymentUrl(url);
  }
  return url!;
}

This means that if I call preloadQuery(api.foo.bla, {}., {url: process.env.MY_VAR}) when MY_VAR is not used the code falls back to NEXT_PUBLIC_CONVEX_URL. It would be better to check whether 'url' in options and default based on that, throwing early if the provided url is undefined.

Fixing this would unfortunately be a breaking change in the strict definition of breaking.

xixixao avatar Dec 16 '24 14:12 xixixao

We'll call it out in the release and make this change, this is just better.

thomasballinger avatar Dec 17 '24 04:12 thomasballinger

never got around to this yet - but would appreciate help if someone wants to send a PR

nipunn1313 avatar Apr 24 '25 18:04 nipunn1313