Next.js Discord

Discord Forum

`redirect()` not working

Unanswered
Saltwater Crocodile posted this in #help-forum
Open in Discord
Saltwater CrocodileOP
I am very new with nextjs and I can't understand the reason why redirect doesnot work as expected in this piece of code.

// imports ...

export const dynamic = "force-dynamic";
export const runtime = "edge";

export default async function ApiPage(props: {
  params: { apiId: string };
  searchParams: {
    interval?: Interval;
  };
}) {
  const tenantId = getTenantId();

  const api = await db.query.apis.findFirst({
    where: (table, { eq, and, isNull }) =>
      and(eq(table.id, props.params.apiId), isNull(table.deletedAt)),
    with: {
      workspace: true,
    },
  });

  console.log({ tenantId, workspaceTenantId: api?.workspace?.tenantId });

  if (!api || api.workspace.tenantId !== tenantId) {
    console.log("!api || api.workspace.tenantId !== tenantId");
    return redirect("/apis");
  }

  // other ...
}

This is the code that renders /apis/[apiId]/page.tsx. In the initial load everything is fine, redirect also works. In the UI I have a way to change the workspace, which changes the tenantId. After this change the apiId becomes invalid, hence api is undefined. Thus the if statement if (!api || api.workspace.tenantId !== tenantId) { executes and i see the log. But the redirect doesnot happen.

What is the reason for this?

2 Replies