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.

On this page:

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

1type StackClientApp = {
2 new(options): StackClientApp; //$stack-link-to:#constructor
3
4 getUser([options]): Promise<User>; //$stack-link-to:#stackclientappgetuseroptions
5 ⤷ useUser([options]): User; //$stack-link-to:#stackclientappuseuseroptions
6 getProject(): Promise<Project>; //$stack-link-to:#stackclientappgetproject
7 ⤷ useProject(): Project; //$stack-link-to:#stackclientappuseproject
8
9 signInWithOAuth(provider): void; //$stack-link-to:#stackclientappsigninwithoauthprovider
10 signInWithCredential([options]): Promise<...>; //$stack-link-to:#stackclientappsigninwithcredentialoptions
11 signUpWithCredential([options]): Promise<...>; //$stack-link-to:#stackclientappsignupwithcredentialoptions
12 sendForgotPasswordEmail(email): Promise<...>; //$stack-link-to:#stackclientappsendforgotpasswordemailemail
13 sendMagicLinkEmail(email): Promise<...>; //$stack-link-to:#stackclientappsendmagiclinkemailemail
14};

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

options
object

An object containing multiple properties.

tokenStore
unionRequired

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.

"nextjs-cookie"

Persists the session tokens in window.cookie in browser environments, or Next.js cookies in server environments. This is the most common choice.

"cookie"

Persists the session tokens in window.cookie in browser environments. Will not read or write cookies on the server.

{ accessToken: string, refreshToken: string }

Reads the initial value for the session tokens from the provided object. It expects the same format as the object returned by currentUser.getAuthJson().

Does not persist changes to the tokens.

Reads the initial value for the session tokens from headers of the request object. For more information, see the documentation for currentUser.getAuthHeaders().

Does not persist changes to the tokens.

baseUrl
string

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.

projectId
string

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.

publishableClientKey
string

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.

urls
object

The URLs that Stack uses to route and redirect.

home
string

The URL of the home page.

signIn
string

The URL of the sign-in page.

afterSignIn
string

The URL that the user will be redirected to after successful signing in.

signUp
string

The URL of the sign-up page.

afterSignUp
string

The URL that the user will be redirected to after successful signing up.

afterSignOut
string

The URL that the user will be redirected to after successful signing out.

emailVerification
string

The URL of the email verification page.

passwordReset
string

The URL of the password reset page.

forgotPassword
string

The URL of the forgot password page.

accountSettings
string

The URL of the account settings page.

handler
string

The URL of the handler root.

noAutomaticPrefetch
boolean

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

1declare new(options: {
2 tokenStore: "nextjs-cookie" | "cookie" | { accessToken: string, refreshToken: string } | Request;
3 baseUrl?: string;
4 projectId?: string;
5 publishableClientKey?: string;
6 urls: {
7 ...
8 };
9 noAutomaticPrefetch?: boolean;
10}): StackClientApp;

Examples

1const stackClientApp = new StackClientApp({
2 tokenStore: "nextjs-cookie",
3 baseUrl: "https://api.stack-auth.com",
4 projectId: "123",
5 publishableClientKey: "123",
6 urls: {
7 home: "/",
8 },
9});

stackClientApp.getUser([options])

Gets the current user.

Parameters

options
object

An object containing multiple properties.

or
"return-null" | "redirect" | "throw"

What to do if the user is not signed in. Defaults to "return-null".

"return-null"

Returns null. The default.

"redirect"

Redirects the user to the signIn URL.

"throw"

Throws an error.

Returns

Promise<CurrentUser | null>: The current user, or null if not signed in. If or is "redirect" or "throw", never returns null.

Signature

1declare function getUser(
2 options: {
3 or?: "return-null" | "redirect" | "throw"
4 }
5): Promise<CurrentUser | null>;

Examples

1const userOrNull = await stackClientApp.getUser();
2console.log(userOrNull); // null if not signed in
3
4const user = await stackClientApp.getUser({ or: "redirect" });
5console.log(user); // always defined; redirects to sign-in page if not signed in

stackClientApp.useUser([options])

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

An object containing multiple properties.

or
"return-null" | "redirect" | "throw"

What to do if the user is not signed in. Defaults to "return-null".

"return-null"

Returns null. The default.

"redirect"

Redirects the user to the signIn URL.

"throw"

Throws an error.

Returns

CurrentUser | null: The current user, or null if not signed in. If or is "redirect" or "throw", never returns null.

Signature

1declare function useUser(
2 options: {
3 or?: "return-null" | "redirect" | "throw"
4 }
5): CurrentUser | null;

Examples

1"use client";
2
3function MyReactComponent() {
4 // useUser(...) is an alias for useStackApp().useUser(...)
5 const user = useUser();
6 return user ? <div>Hello, {user.name}</div>
7 : <div>Not signed in</div>;
8}

stackClientApp.getProject()

Gets the current project.

Parameters

No parameters.

Returns

Promise<Project>: The current project.

Signature

1declare function getProject(): Promise<Project>;

Examples

1const project = await stackClientApp.getProject();

stackClientApp.useProject()

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

Parameters

No parameters.

Returns

Project: The current project.

Signature

1declare function useProject(): Project;

Examples

1function MyReactComponent() {
2 const project = useProject();
3}

stackClientApp.signInWithOAuth(provider)

Initiates the OAuth sign-in process with the specified provider. This method:

  1. Redirects the user to the OAuth provider’s sign-in page.
  2. After successful authentication, redirects the user back to your application.
  3. The final redirect destination is determined as follows:
    • If an after_auth_return_to query parameter was provided when calling this function, it uses that URL.
    • Otherwise, it uses the afterSignIn URL configured in the app settings.

Parameters

provider
stringRequired

The type of the OAuth provider to sign in with.

Returns

Promise<void>.

Signature

1declare function signInWithOAuth(provider: string): Promise<void>;

Examples

1await stackClientApp.signInWithOAuth("google");

stackClientApp.signInWithCredential([options])

Sign in using email and password credentials. The behavior is as follows:

  1. If sign-in is successful:

    • By default, redirects the user to the afterSignIn URL.
    • If after_auth_return_to is provided in the query parameters, redirects to that URL instead.
    • If noRedirect is set to true, it will not redirect and instead return a success Result object.
  2. If sign-in fails:

    • No redirection occurs.
    • Returns a Result object containing error information.

Parameters

options
object

An object containing multiple properties.

email
stringRequired

The email of the user to sign in with.

password
stringRequired

The password of the user to sign in with.

noRedirect
boolean

Whether to not redirect the user after sign-in. Defaults to false.

Returns

Promise<Result<undefined, KnownErrors["EmailPasswordMismatch"]>>: A promise that resolves to a Result object.

Signature

1declare function signInWithCredential(options: {
2 email: string;
3 password: string;
4 noRedirect?: boolean;
5}): Promise<Result<undefined, KnownErrors["EmailPasswordMismatch"]>>;

Examples

1const result = await stackClientApp.signInWithCredential({
2 email: "test@example.com",
3 password: "password",
4});
5
6if (result.status === "error") {
7 console.error("Sign in failed", result.error.message);
8}

stackClientApp.signUpWithCredential([options])

Sign up using email and password credentials. The behavior is as follows:

  1. If sign-up is successful:

    • By default, redirects the user to the afterSignUp URL.
    • If after_auth_return_to is provided in the query parameters, redirects to that URL instead.
    • If noRedirect is set to true, it will not redirect and instead return a success Result object.
  2. If sign-up fails:

    • No redirection occurs.
    • Returns a Result object containing error information.

Parameters

options
object

An object containing multiple properties.

email
stringRequired

The email of the user to sign up with.

password
stringRequired

The password of the user to sign up with.

noRedirect
boolean

Whether to not redirect the user after sign-up. Defaults to false.

Returns

Promise<Result<undefined, KnownErrors["UserEmailAlreadyExists"] | KnownErrors["PasswordRequirementsNotMet"]>>: A promise that resolves to a Result object.

Signature

1declare function signUpWithCredential(options: {
2 email: string;
3 password: string;
4 noRedirect?: boolean;
5}): Promise<Result<undefined, KnownErrors["UserEmailAlreadyExists"] | KnownErrors["PasswordRequirementsNotMet"]>>;

Examples

1const result = await stackClientApp.signUpWithCredential({
2 email: "test@example.com",
3 password: "password",
4});
5
6if (result.status === "error") {
7 console.error("Sign up failed", result.error.message);
8}

stackClientApp.sendForgotPasswordEmail(email)

Send a forgot password email to an email address.

Parameters

email
stringRequired

The email of the user to send the forgot password email to.

Returns

Promise<Result<undefined, KnownErrors["UserNotFound"]>>: A promise that resolves to a Result object.

Signature

1declare function sendForgotPasswordEmail(email: string): Promise<Result<undefined, KnownErrors["UserNotFound"]>>;

Examples

1const result = await stackClientApp.sendForgotPasswordEmail("test@example.com");
2
3if (result.status === "success") {
4 console.log("Forgot password email sent");
5} else {
6 console.error("Failed to send forgot password email", result.error.message);
7}

stackClientApp.sendMagicLinkEmail(email)

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

Parameters

email
stringRequired

The email of the user to send the magic link email to.

Returns

Promise<Result<{ nonce: string }, KnownErrors["RedirectUrlNotWhitelisted"]>>: A promise that resolves to a Result object.

Signature

1declare function sendMagicLinkEmail(email: string): Promise<Result<{ nonce: string }, KnownErrors["RedirectUrlNotWhitelisted"]>>;

Examples

1const 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

1type StackServerApp =
2 // Inherits all functionality from StackClientApp
3 & StackClientApp //$stack-link-to:#stackclientapp
4 & {
5 new(options): StackServerApp; //$stack-link-to:#constructor-1
6
7 getUser([id][, options]): Promise<ServerUser | null>; //$stack-link-to:#stackserverappgetuserid-options
8 ⤷ useUser([id][, options]): ServerUser; //$stack-link-to:#stackserverappuseuserid-options
9 listUsers([options]): Promise<ServerUser[]>; //$stack-link-to:#stackserverapplistusersoptions
10 ⤷ useUsers([options]): ServerUser[]; //$stack-link-to:#stackserverappuseusersoptions
11 createUser([options]): Promise<ServerUser>; //$stack-link-to:#stackserverappcreateuseroptions
12
13 getTeam(id): Promise<ServerTeam | null>; //$stack-link-to:#stackserverappgetteamid
14 ⤷ useTeam(id): ServerTeam; //$stack-link-to:#stackserverappuseteamid
15 listTeams(): Promise<ServerTeam[]>; //$stack-link-to:#stackserverapplistteams
16 ⤷ useTeams(): ServerTeam[]; //$stack-link-to:#stackserverappuseteams
17 createTeam([options]): Promise<ServerTeam>; //$stack-link-to:#stackserverappcreateteamoptions
18 }

Constructor

Parameters

options
object

An object containing multiple properties.

tokenStore
unionRequired

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.

"nextjs-cookie"

Persists the session tokens in window.cookie in browser environments, or Next.js cookies in server environments. This is the most common choice.

"cookie"

Persists the session tokens in window.cookie in browser environments. Will not read or write cookies on the server.

{ accessToken: string, refreshToken: string }

Reads the initial value for the session tokens from the provided object. It expects the same format as the object returned by currentUser.getAuthJson().

Does not persist changes to the tokens.

Reads the initial value for the session tokens from headers of the request object. For more information, see the documentation for currentUser.getAuthHeaders().

Does not persist changes to the tokens.

baseUrl
string

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.

projectId
string

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.

publishableClientKey
string

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.

secretServerKey
string

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.

urls
object

The URLs that Stack uses to route and redirect.

home
string

The URL of the home page.

signIn
string

The URL of the sign-in page.

afterSignIn
string

The URL that the user will be redirected to after successful signing in.

signUp
string

The URL of the sign-up page.

afterSignUp
string

The URL that the user will be redirected to after successful signing up.

afterSignOut
string

The URL that the user will be redirected to after successful signing out.

emailVerification
string

The URL of the email verification page.

passwordReset
string

The URL of the password reset page.

forgotPassword
string

The URL of the forgot password page.

accountSettings
string

The URL of the account settings page.

handler
string

The URL of the handler root.

noAutomaticPrefetch
boolean

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

1declare new(options: {
2 tokenStore: "nextjs-cookie" | "cookie" | { accessToken: string, refreshToken: string } | Request;
3 baseUrl?: string;
4 projectId?: string;
5 publishableClientKey?: string;
6 secretServerKey?: string;
7 urls: {
8 ...
9 };
10 noAutomaticPrefetch?: boolean;
11}): StackServerApp;

Examples

1const stackServerApp = new StackServerApp({
2 tokenStore: "nextjs-cookie",
3 urls: {
4 signIn: '/my-custom-sign-in-page',
5 },
6});

stackServerApp.getUser([id], [options])

Similar to StackClientApp.getUser(), but:

  • Returns a ServerUser, which is more powerful
  • Has an additional overload that takes an id parameter instead of options, returning the user with the given ID instead of the current user.

Parameters

id
string

The ID of the user to get.

options
object

An object containing multiple properties.

or
"return-null" | "redirect" | "throw"

What to do if the user is not signed in. Defaults to "return-null".

"return-null"

Returns null. The default.

"redirect"

Redirects the user to the signIn URL.

"throw"

Throws an error.

Returns

Promise<ServerUser | null>: The user, or null if not found. If id is not provided, returns a CurrentServerUser.

If id is not provided and or is "redirect" or "throw", never returns null.

Signature

1// This function has two overloads:
2declare function getUser(id: string): Promise<ServerUser | null>;
3declare function getUser(
4 options: {
5 or?: "return-null" | "redirect" | "throw"
6 }
7): Promise<CurrentServerUser | null>;

Examples

1const user = await stackServerApp.getUser();
2console.log(user); // CurrentServerUser

stackServerApp.useUser([id][, options])

This is the documentation for a React hook on a server type. This is uncommon, because server types are only available with server permissions and React Server Components do not use hooks. Ask yourself if you:

  • Want to use this on the server, eg. in a React Server Component? Look for the respective function without the use prefix (eg. getUser instead of useUser).
  • Want to use this on the client, eg. in a React Client Component? Look at the documentation of the client type (eg. CurrentUser instead of CurrentServerUser).
  • Are an advanced user, building an internal tool, and confident that you are securing SECRET_SERVER_KEY correctly? Then this is for you.

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

stackServerApp.listUsers([options])

Lists all users on the project.

Parameters

options
object

An object containing multiple properties.

cursor
string

The cursor to start the result set from.

limit
number

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.

desc
booleanDefaults to false

Whether to sort the results in descending order.

query
string

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

Returns

Promise<ServerUser[]>: The list of users. The array has an additional nextCursor property, which is the cursor to the next page of users if limit is provided.

Signature

1declare function listUsers(options: {
2 cursor?: string;
3 limit?: number;
4 orderBy?: "signedUpAt";
5 desc?: boolean;
6 query?: string;
7}): Promise<ServerUser[] & { nextCursor: string | null }>;

Examples

1const users = await stackServerApp.listUsers({ limit: 20 });
2console.log(users);
3
4if (users.nextCursor) {
5 const nextPageUsers = await stackServerApp.listUsers({ cursor: users.nextCursor, limit: 20 });
6 console.log(nextPageUsers);
7}

stackServerApp.useUsers([options])

This is the documentation for a React hook on a server type. This is uncommon, because server types are only available with server permissions and React Server Components do not use hooks. Ask yourself if you:

  • Want to use this on the server, eg. in a React Server Component? Look for the respective function without the use prefix (eg. getUser instead of useUser).
  • Want to use this on the client, eg. in a React Client Component? Look at the documentation of the client type (eg. CurrentUser instead of CurrentServerUser).
  • Are an advanced user, building an internal tool, and confident that you are securing SECRET_SERVER_KEY correctly? Then this is for you.

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

stackServerApp.createUser([options])

Creates a new user from the server.

Note that this function is meant for server-side code; on the client, use any of the signInWithXyz or signUpWithXyz functions instead.

Parameters

options
object

An object containing multiple properties.

primaryEmail
string

The primary email of the user to create.

primaryEmailVerified
boolean

Whether the primary email is verified. Defaults to false.

primaryEmailAuthEnabled
boolean

Whether the primary email is enabled. When using password or otp auth, this must be set to true, otherwise the user will not be able to sign in.

password
string

The password for the new user. An error will be thrown if a password is provided but password authentication is not enabled for the project in the dashboard.

otpAuthEnabled
boolean

Enables OTP (One-Time Password) or magic link sign-in using the primary email. Note: Only verified emails can be used for OTP sign-in. An error will be thrown if set to true when OTP authentication is not enabled in the dashboard.

displayName
string

The display name of the user to create.

Returns

Promise<ServerUser>: The created user.

Signature

1declare function createUser(options: {
2 primaryEmail?: string;
3 primaryEmailVerified?: boolean;
4 primaryEmailAuthEnabled?: boolean;
5 password?: string;
6 otpAuthEnabled?: boolean;
7 displayName?: string;
8}): Promise<ServerUser>;

Examples

1const user = await stackServerApp.createUser({
2 primaryEmail: "test@example.com",
3 primaryEmailAuthEnabled: true,
4 password: "password123",
5});

stackServerApp.getTeam(id)

Get a team by its ID.

Parameters

id
stringRequired

The ID of the team to get.

Returns

Promise<ServerTeam | null>: The team, or null if not found.

Signature

1declare function getTeam(id: string): Promise<ServerTeam | null>;

Examples

1const team = await stackServerApp.getTeam("team_id_123");
2console.log(team); // null if not found

stackServerApp.useTeam(id)

This is the documentation for a React hook on a server type. This is uncommon, because server types are only available with server permissions and React Server Components do not use hooks. Ask yourself if you:

  • Want to use this on the server, eg. in a React Server Component? Look for the respective function without the use prefix (eg. getUser instead of useUser).
  • Want to use this on the client, eg. in a React Client Component? Look at the documentation of the client type (eg. CurrentUser instead of CurrentServerUser).
  • Are an advanced user, building an internal tool, and confident that you are securing SECRET_SERVER_KEY correctly? Then this is for you.

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

stackServerApp.listTeams()

Lists all teams on the current project.

Parameters

None.

Returns

Promise<ServerTeam[]>: All teams on the current project.

Signature

1declare function listTeams(): Promise<ServerTeam[]>;

Examples

1const teams = await stackServerApp.listTeams();
2console.log(teams);

stackServerApp.useTeams()

This is the documentation for a React hook on a server type. This is uncommon, because server types are only available with server permissions and React Server Components do not use hooks. Ask yourself if you:

  • Want to use this on the server, eg. in a React Server Component? Look for the respective function without the use prefix (eg. getUser instead of useUser).
  • Want to use this on the client, eg. in a React Client Component? Look at the documentation of the client type (eg. CurrentUser instead of CurrentServerUser).
  • Are an advanced user, building an internal tool, and confident that you are securing SECRET_SERVER_KEY correctly? Then this is for you.

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

stackServerApp.createTeam([options])

Creates a team.

This is different from user.createTeam() because it does not add a user to the team. The newly created team will not have a creator.

Parameters

data
objectRequired
displayName
string

The display name for the team.

profileImageUrl
string | null

The URL of the team’s profile image (base64 image allowed, crop and compress before passing it in), or null to remove.

Returns

Promise<ServerTeam>: The created team.

Signature

1declare function createTeam(data: {
2 displayName: string;
3 profileImageUrl?: string | null;
4}): Promise<ServerTeam>;

Examples

1const team = await stackServerApp.createTeam({
2 displayName: "New Team",
3 profileImageUrl: "https://example.com/profile.jpg",
4});
Built with