SimpleAuth
ReactComponents

SignedOut

Render children only when there is no active session.

Overview

SignedOut renders children only when there is no active session. While the session snapshot is loading it renders nothing. Use Show when you need an explicit loading fallback or an email-verified branch.

Preview

Interactive preview requires JavaScript.

Install

npx @simpleauthjs/react add session

Props

NameTypeRequiredDescription
childrenReactNodeYesShown when the user is not signed in.

Usage

"use client"

import { SignedOut } from "@/components/simpleauth"
import Link from "next/link"

export function AuthLinks() {
  return (
    <SignedOut>
      <Link href="/login">Sign in</Link>
    </SignedOut>
  )
}

Source

SignedOut ships with the session feature. The files below match what npx @simpleauthjs/react add session writes.

components/simpleauth/hooks/use-current-user.ts
"use client"

import { useCallback, useEffect, useState } from "react"
import { SimpleAuthError, type MeResponse } from "@simpleauthjs/core"
import { useSimpleAuthClient } from "../provider"

type UseCurrentUserOptions = {
  autoLoad?: boolean
}

function getErrorMessage(error: unknown) {
  if (error instanceof SimpleAuthError) {
    return error.message
  }

  if (error instanceof Error) {
    return error.message
  }

  return "Unable to fetch current user."
}

export function useCurrentUser(options: UseCurrentUserOptions = {}) {
  const { autoLoad = true } = options
  const auth = useSimpleAuthClient()
  const [isLoading, setIsLoading] = useState(Boolean(autoLoad))
  const [error, setError] = useState<string | null>(null)
  const [data, setData] = useState<MeResponse | null>(null)

  const refresh = useCallback(async () => {
    setIsLoading(true)
    setError(null)

    try {
      const response = await auth.me()
      setData(response)
      return response
    } catch (requestError) {
      setData(null)
      setError(getErrorMessage(requestError))
      throw requestError
    } finally {
      setIsLoading(false)
    }
  }, [auth])

  useEffect(() => {
    if (!autoLoad) {
      return
    }

    refresh().catch(() => {})
  }, [autoLoad, refresh])

  return {
    refresh,
    data,
    error,
    isError: Boolean(error),
    isLoading,
  }
}

On this page