Next.js Discord

Discord Forum

error when redirecting user

Unanswered
Briard posted this in #help-forum
Open in Discord
BriardOP
 import { db } from "..";
import { user } from "@/db/schema/user";
import { count, sql } from "drizzle-orm";
import { redirect } from "next/navigation";

export async function fetchUsersLength() {
  "use server";
  try {
    const [{ count: userLength }] = await db
      .select({ count: count() })
      .from(user);
    if (userLength > 0) {
      redirect("/sign-in");
    }
  } catch (err) {
    if (err instanceof Error) console.log(err.stack);
  }
}


this function should kick the user from register page (server component) , if there is users in the database but this error is appearing

Error: NEXT_REDIRECT
    at getRedirectError (/Users/y7gn/Downloads/github/ultimate-project-managment/.next/server/chunks/ssr/node_modules_554be4._.js:10069:19)
    at redirect (/Users/y7gn/Downloads/github/ultimate-project-managment/.next/server/chunks/ssr/node_modules_554be4._.js:10076:11)
    at fetchUsersLength (/Users/y7gn/Downloads/github/ultimate-project-managment/.next/server/chunks/ssr/[root of the server]__3d7cd1._.js:209:211)
    at process.processTicksAndRejections (node:internal/process/task_queues:105:5)
    at async Register (/Users/y7gn/Downloads/github/ultimate-project-managment/.next/server/chunks/ssr/[root of the server]__3d7cd1._.js:237:5)

2 Replies

BriardOP
it appears that
The redirect() is never supposed to be used in try/catch blocks.

i had to return the count and do redirect on my server component