convex-backend
convex-backend copied to clipboard
Next.js SDK bad URL defaulting
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.
We'll call it out in the release and make this change, this is just better.
never got around to this yet - but would appreciate help if someone wants to send a PR