Next.js Discord

Discord Forum

How do I detect if I'm on React Server Component, or on Route Handler?

Unanswered
American black bear posted this in #help-forum
Open in Discord
American black bearOP
I want to detect if I'm on React Server Component or Route Handler, because cookies() function is only available in Route Handler.
// creates a new session with extended duration if the function is called from Route Handler
const session = getServerSesison()


Current implementation:
export async function getServerSession(): Promise<SessionValidationResult> {
  const cookieStore = await cookies()
  const session = cookieStore.get("session")
  if (!session) {
    return { success: false, session: null, user: null, error: { message: "Not logged in" } }
  }

  const result = await validateSessionToken(session.value)
  if (result.success) {
    try {
      const token = generateSessionToken()
      await setSessionCookie(token, await createSession(token, result.user.id))
    } catch {
      // ignore if this function is called from React server components
    }
  } else {
    cookieStore.delete("session")
  }

  return result
}


What I want:
export async function getServerSession(): Promise<SessionValidationResult> {
  const cookieStore = await cookies()
  const session = cookieStore.get("session")
  if (!session) {
    return { success: false, session: null, user: null, error: { message: "Not logged in" } }
  }

  const result = await validateSessionToken(session.value)
  if (!result.success) {
    cookieStore.delete("session")
  } else if (isRouteHandler()) {
    const token = generateSessionToken()
    await setSessionCookie(token, await createSession(token, result.user.id))
  }

  return result
}

3 Replies

if you call that utility function from /app/**/page.tsx and/or any components that’s async and (obviously) not marked with “use client” then you’re in a React Server Component.

If you’re inside a file with route.ts you’re in a Route Handler.
@American black bear any updates?