StackApp

This is a detailed reference for the StackApp object. If you're looking for a more high-level overview, please read the respective page in the Concepts section.

Overview


StackClientApp

A StackApp with client-level permissions. It contains most of the useful methods and hooks for your client-side code.

Most commonly you get an instance of StackClientApp by calling useStackApp() in a Client Component.

Table of Contents

Constructor

Creates a new StackClientApp instance.

Because each app creates a new connection to Stack Auth's backend, you should re-use existing instances wherever possible.

This object is not usually constructed directly. More commonly, you would construct a StackServerApp instead, pass it into a <StackProvider />, and then use useStackApp() hook to obtain a StackClientApp.

The setup wizard does these steps for you, so you don't need to worry about it unless you are manually setting up Stack Auth.

If you're building a client-only app and don't have a SECRET_SERVER_KEY, you can construct a StackClientApp directly.

Parameters:

optionsobject

An object containing multiple properties.

Show Parameters
tokenStoreunionrequired
Where to store the user's session tokens. In most cases, this is `"nextjs-cookie"`, which will store the tokens in cookies using Next.js.
Show possible values
"nextjs-cookie"string
Persists the session tokens in `window.cookie` in browser environments, or Next.js cookies in server environments. This is the most common choice.
"cookie"string
Persists the session tokens in `window.cookie` in browser environments. Will not read or write cookies on the server.
{ accessToken: string, refreshToken: string }object
Reads the initial value for the session tokens from the provided object. It expects the same format as the object returned by [`currentUser.getAuthJson()`](../types/user.mdx#getauthjson). Does not persist changes to the tokens.
Requestobject
Reads the initial value for the session tokens from headers of the request object. For more information, see the documentation for [`currentUser.getAuthHeaders()`](../types/user.mdx#getauthheaders). Does not persist changes to the tokens.
baseUrlstring
The base URL for Stack Auth's API. Only override this if you are self-hosting Stack Auth. Defaults to `https://api.stack-auth.com`, unless overridden by the `NEXT_PUBLIC_STACK_API_URL` environment variable.
projectIdstring
The ID of the project that the app is associated with, as found on Stack Auth's dashboard. Defaults to the value of the `NEXT_PUBLIC_STACK_PROJECT_ID` environment variable.
publishableClientKeystring
The publishable client key of the app, as found on Stack Auth's dashboard. Defaults to the value of the `NEXT_PUBLIC_STACK_PUBLISHABLE_CLIENT_KEY` environment variable.
urlsobject
The URLs that Stack uses to route and redirect.
Show properties
homestring
The URL of the home page.
signInstring
The URL of the sign-in page.
afterSignInstring
The URL that the user will be redirected to after successful signing in.
signUpstring
The URL of the sign-up page.
afterSignUpstring
The URL that the user will be redirected to after successful signing up.
afterSignOutstring
The URL that the user will be redirected to after successful signing out.
emailVerificationstring
The URL of the email verification page.
passwordResetstring
The URL of the password reset page.
forgotPasswordstring
The URL of the forgot password page.
accountSettingsstring
The URL of the account settings page.
handlerstring
The URL of the handler root.
noAutomaticPrefetchboolean
By default, the Stack app will automatically prefetch some data from Stack's server when this app is first constructed. Those network requests may be unnecessary if the app is never used or disposed of immediately. By setting this option to `true`, you can disable the prefetching behavior.
Signature
declare new(options: {
  tokenStore: "nextjs-cookie" | "cookie" | { accessToken: string, refreshToken: string } | Request;
  baseUrl?: string;
  projectId?: string;
  publishableClientKey?: string;
  urls: {
    ...
  };
  noAutomaticPrefetch?: boolean;
}): StackClientApp;
Examples
const stackClientApp = new StackClientApp({
  tokenStore: "nextjs-cookie",
  baseUrl: "https://api.stack-auth.com",
  projectId: "123",
  publishableClientKey: "123",
  urls: {
    home: "/",
  },
});

Gets the current user.

Parameters:

  • options? (object) - Optional configuration
    • or? - What to do if user not found: "return-null" | "redirect" | "throw"

Returns: Promise<CurrentUser | null> - The current user, or null if not signed in

Signature
declare function getUser(
  options?: {
    or?: "return-null" | "redirect" | "throw"
  }
): Promise<CurrentUser | null>;
Examples
// Basic usage
const userOrNull = await stackClientApp.getUser();
console.log(userOrNull); // null if not signed in

// With redirect on no user
const user = await stackClientApp.getUser({ or: "redirect" });
console.log(user); // always defined; redirects to sign-in page if not signed in

React hook version of getUser(). Functionally equivalent to getUser(), but as a React hook.

Equivalent to the useUser() standalone hook (which is an alias for useStackApp().useUser()).

Parameters:

  • options? (object) - Same as getUser()

Returns: CurrentUser | null

Signature
declare function useUser(
  options?: {
    or?: "return-null" | "redirect" | "throw"
  }
): CurrentUser | null;
Examples
"use client";

function MyReactComponent() {
  const user = useUser();
  return user ? <div>Hello, {user.name}</div>
              : <div>Not signed in</div>;
}

Gets the current project.

Parameters:

  • No parameters

Returns: Promise<Project>

Signature
declare function getProject(): Promise<Project>;
Examples
const project = await stackClientApp.getProject();

React hook version of getProject().

Parameters:

  • No parameters

Returns: Project

Signature
declare function useProject(): Project;
Examples

getting the current project in a react component

function MyReactComponent() {
  const project = useProject();
}

Initiates the OAuth sign-in process with the specified provider.

Parameters:

  • provider (string) - The OAuth provider type

Returns: Promise<void>

Signature
declare function signInWithOAuth(provider: string): Promise<void>;
Examples
await stackClientApp.signInWithOAuth("google");

Sign in using email and password credentials.

Parameters:

  • options (object)
    • email (string) - User's email
    • password (string) - User's password
    • noRedirect? (boolean) - Whether to skip redirect after sign-in

Returns: Promise<Result<undefined, KnownErrors["EmailPasswordMismatch"]>>

Signature
declare function signInWithCredential(options: {
  email: string;
  password: string;
  noRedirect?: boolean;
}): Promise<Result<undefined, KnownErrors["EmailPasswordMismatch"]>>;
Examples
const result = await stackClientApp.signInWithCredential({
  email: "test@example.com",
  password: "password",
});

if (result.status === "error") {
  console.error("Sign in failed", result.error.message);
}

Sign up using email and password credentials.

Parameters:

  • options (object)
    • email (string) - User's email
    • password (string) - User's password
    • noRedirect? (boolean) - Whether to skip redirect after sign-up

Returns: Promise<Result<undefined, KnownErrors["UserWithEmailAlreadyExists"] | KnownErrors["PasswordRequirementsNotMet"]>>

Signature
declare function signUpWithCredential(options: {
  email: string;
  password: string;
  noRedirect?: boolean;
}): Promise<Result<undefined, KnownErrors["UserWithEmailAlreadyExists"] | KnownErrors["PasswordRequirementsNotMet"]>>;
Examples
const result = await stackClientApp.signUpWithCredential({
  email: "test@example.com",
  password: "password",
});

if (result.status === "error") {
  console.error("Sign up failed", result.error.message);
}

Send a forgot password email to an email address.

Parameters:

  • email (string) - The email to send the forgot password email to

Returns: Promise<Result<undefined, KnownErrors["UserNotFound"]>>

Signature
declare function sendForgotPasswordEmail(email: string): Promise<Result<undefined, KnownErrors["UserNotFound"]>>;
Examples
const result = await stackClientApp.sendForgotPasswordEmail("test@example.com");

if (result.status === "success") {
  console.log("Forgot password email sent");
} else {
  console.error("Failed to send forgot password email", result.error.message);
}

Send a magic link/OTP sign-in email to an email address.

Parameters:

  • email (string) - The email to send the magic link to

Returns: Promise<Result<{ nonce: string }, KnownErrors["RedirectUrlNotWhitelisted"]>>

Signature
declare function sendMagicLinkEmail(email: string): Promise<Result<{ nonce: string }, KnownErrors["RedirectUrlNotWhitelisted"]>>;
Examples
const result = await stackClientApp.sendMagicLinkEmail("test@example.com");

StackServerApp

Like StackClientApp, but with server permissions. Has full read and write access to all users.

Since this functionality should only be available in environments you trust (ie. your own server), it requires a SECRET_SERVER_KEY. In some cases, you may want to use a StackServerApp on the client; an example for this is an internal dashboard that only your own employees have access to. We generally recommend against doing this unless you are aware of and protected against the (potentially severe) security implications of exposing SECRET_SERVER_KEY on the client.

Table of Contents

Constructor

Creates a new StackClientApp instance.

Parameters:

optionsobject

An object containing multiple properties.

Show Parameters
tokenStoreunionrequired
Where to store the user's session tokens. In most cases, this is `"nextjs-cookie"`, which will store the tokens in cookies using Next.js.
Show possible values
"nextjs-cookie"string
Persists the session tokens in `window.cookie` in browser environments, or Next.js cookies in server environments. This is the most common choice.
"cookie"string
Persists the session tokens in `window.cookie` in browser environments. Will not read or write cookies on the server.
{ accessToken: string, refreshToken: string }object
Reads the initial value for the session tokens from the provided object. It expects the same format as the object returned by [`currentUser.getAuthJson()`](../types/user.mdx#getauthjson). Does not persist changes to the tokens.
Requestobject
Reads the initial value for the session tokens from headers of the request object. For more information, see the documentation for [`currentUser.getAuthHeaders()`](../types/user.mdx#getauthheaders). Does not persist changes to the tokens.
baseUrlstring
The base URL for Stack Auth's API. Only override this if you are self-hosting Stack Auth. Defaults to `https://api.stack-auth.com`, unless overridden by the `NEXT_PUBLIC_STACK_API_URL` environment variable.
projectIdstring
The ID of the project that the app is associated with, as found on Stack Auth's dashboard. Defaults to the value of the `NEXT_PUBLIC_STACK_PROJECT_ID` environment variable.
publishableClientKeystring
The publishable client key of the app, as found on Stack Auth's dashboard. Defaults to the value of the `NEXT_PUBLIC_STACK_PUBLISHABLE_CLIENT_KEY` environment variable.
secretServerKeystring

The secret server key of the app, as found on Stack Auth's dashboard. Defaults to the value of the SECRET_SERVER_KEY environment variable.

urlsobject
The URLs that Stack uses to route and redirect.
Show properties
homestring
The URL of the home page.
signInstring
The URL of the sign-in page.
afterSignInstring
The URL that the user will be redirected to after successful signing in.
signUpstring
The URL of the sign-up page.
afterSignUpstring
The URL that the user will be redirected to after successful signing up.
afterSignOutstring
The URL that the user will be redirected to after successful signing out.
emailVerificationstring
The URL of the email verification page.
passwordResetstring
The URL of the password reset page.
forgotPasswordstring
The URL of the forgot password page.
accountSettingsstring
The URL of the account settings page.
handlerstring
The URL of the handler root.
noAutomaticPrefetchboolean
By default, the Stack app will automatically prefetch some data from Stack's server when this app is first constructed. Those network requests may be unnecessary if the app is never used or disposed of immediately. By setting this option to `true`, you can disable the prefetching behavior.
Signature
declare new(options: {
  tokenStore: "nextjs-cookie" | "cookie" | { accessToken: string, refreshToken: string } | Request;
  baseUrl?: string;
  projectId?: string;
  publishableClientKey?: string;
  urls: {
    ...
  };
  noAutomaticPrefetch?: boolean;
}): StackServerApp;
Examples
const stackServerApp = new StackServerApp({
  tokenStore: "nextjs-cookie",
  urls: {
    signIn: '/my-custom-sign-in-page',
  },
});

Enhanced version of StackClientApp.getUser() with server permissions.

Overloads:

  1. getUser(id: string): Promise<ServerUser | null> - Get user by ID
  2. getUser(options?: { or?: "return-null" | "redirect" | "throw" }): Promise<CurrentServerUser | null> - Get current user
Signature
// This function has two overloads:
declare function getUser(id: string): Promise<ServerUser | null>;
declare function getUser(
  options?: {
    or?: "return-null" | "redirect" | "throw"
  }
): Promise<CurrentServerUser | null>;
Examples
const user = await stackServerApp.getUser();
console.log(user); // CurrentServerUser

Functionally equivalent to getUser(), but as a React hook.

This should be used on the server-side only.

Lists all users on the project.

Parameters:

optionsobject

An object containing multiple properties.

Show options properties
cursorstring

The cursor to start the result set from.

limitnumber

The maximum number of items to return. If not provided, it will return all users.

orderBy'signedUpAt'

The field to sort the results by. Currently, only signedUpAt is supported.

descboolean

Whether to sort the results in descending order.

querystring

A query to filter the results by. This is a free-text search on the user's display name and emails.

Returns: Promise<ServerUser[] & { nextCursor: string | null }>

Signature
declare function listUsers(options?: {
  cursor?: string;
  limit?: number;
  orderBy?: "signedUpAt";
  desc?: boolean;
  query?: string;
}): Promise<ServerUser[] & { nextCursor: string | null }>;
Examples
const users = await stackServerApp.listUsers({ limit: 20 });
console.log(users);

if (users.nextCursor) {
  const nextPageUsers = await stackServerApp.listUsers({ 
    cursor: users.nextCursor, 
    limit: 20 
  });
  console.log(nextPageUsers);
}

Functionally equivalent to listUsers(), but as a React hook.

This should be used on the server-side only.

Creates a new user from the server.

Parameters:

  • options? (object)
    • primaryEmail? (string) - User's primary email
    • primaryEmailVerified? (boolean) - Whether email is verified
    • primaryEmailAuthEnabled? (boolean) - Whether email auth is enabled
    • password? (string) - User's password
    • otpAuthEnabled? (boolean) - Enable OTP/magic link auth
    • displayName? (string) - User's display name

Returns: Promise<ServerUser>

Signature
declare function createUser(options?: {
  primaryEmail?: string;
  primaryEmailVerified?: boolean;
  primaryEmailAuthEnabled?: boolean;
  password?: string;
  otpAuthEnabled?: boolean;
  displayName?: string;
}): Promise<ServerUser>;
Examples
const user = await stackServerApp.createUser({
  primaryEmail: "test@example.com",
  primaryEmailAuthEnabled: true,
  password: "password123",
});

Team Management

Get a team by its ID.

Parameters:

  • id (string) - Team ID

Returns: Promise<ServerTeam | null>

Signature
declare function getTeam(id: string): Promise<ServerTeam | null>;
Examples
const team = await stackServerApp.getTeam("team_id_123");

Functionally equivalent to getTeam(id), but as a React hook.

This should be used on the server-side only.

Lists all teams on the current project.

Returns: Promise<ServerTeam[]>

Signature
declare function listTeams(): Promise<ServerTeam[]>;
Examples
const teams = await stackServerApp.listTeams();
console.log(teams);

Functionally equivalent to listTeams(), but as a React hook.

This should be used on the server-side only.

Creates a team without adding a user to it.

Parameters:

  • data (object)
    • displayName (string) - Team display name
    • profileImageUrl? (string | null) - Team profile image URL

Returns: Promise<ServerTeam>

Signature
declare function createTeam(data: {
  displayName: string;
  profileImageUrl?: string | null;
}): Promise<ServerTeam>;
Examples
const team = await stackServerApp.createTeam({
  displayName: "New Team",
  profileImageUrl: "https://example.com/profile.jpg",
});

Stack Auth AI

Documentation assistant

Experimental: AI responses may not always be accurate—please verify important details.

For the most accurate information, please join our Discord or email us.

How can I help?

Ask me about Stack Auth while you browse the docs.