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 - Client-level permissions for frontend code
- StackServerApp - Server-level permissions with full access
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:
options
objectAn object containing multiple properties.
Show Parameters
tokenStore
unionrequiredShow possible values
"nextjs-cookie"
string"cookie"
string{ accessToken: string, refreshToken: string }
objectRequest
objectbaseUrl
stringprojectId
stringpublishableClientKey
stringurls
objectShow properties
home
stringsignIn
stringafterSignIn
stringsignUp
stringafterSignUp
stringafterSignOut
stringemailVerification
stringpasswordReset
stringforgotPassword
stringaccountSettings
stringhandler
stringnoAutomaticPrefetch
booleandeclare new(options: {
tokenStore: "nextjs-cookie" | "cookie" | { accessToken: string, refreshToken: string } | Request;
baseUrl?: string;
projectId?: string;
publishableClientKey?: string;
urls: {
...
};
noAutomaticPrefetch?: boolean;
}): StackClientApp;
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 configurationor?
- What to do if user not found:"return-null"
|"redirect"
|"throw"
Returns: Promise<CurrentUser | null>
- The current user, or null
if not signed in
declare function getUser(
options?: {
or?: "return-null" | "redirect" | "throw"
}
): Promise<CurrentUser | null>;
// 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 asgetUser()
Returns: CurrentUser | null
declare function useUser(
options?: {
or?: "return-null" | "redirect" | "throw"
}
): CurrentUser | null;
"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>
declare function getProject(): Promise<Project>;
const project = await stackClientApp.getProject();
React hook version of getProject()
.
Parameters:
- No parameters
Returns: Project
declare function useProject(): Project;
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>
declare function signInWithOAuth(provider: string): Promise<void>;
await stackClientApp.signInWithOAuth("google");
Sign in using email and password credentials.
Parameters:
options
(object)email
(string) - User's emailpassword
(string) - User's passwordnoRedirect?
(boolean) - Whether to skip redirect after sign-in
Returns: Promise<Result<undefined, KnownErrors["EmailPasswordMismatch"]>>
declare function signInWithCredential(options: {
email: string;
password: string;
noRedirect?: boolean;
}): Promise<Result<undefined, KnownErrors["EmailPasswordMismatch"]>>;
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 emailpassword
(string) - User's passwordnoRedirect?
(boolean) - Whether to skip redirect after sign-up
Returns: Promise<Result<undefined, KnownErrors["UserWithEmailAlreadyExists"] | KnownErrors["PasswordRequirementsNotMet"]>>
declare function signUpWithCredential(options: {
email: string;
password: string;
noRedirect?: boolean;
}): Promise<Result<undefined, KnownErrors["UserWithEmailAlreadyExists"] | KnownErrors["PasswordRequirementsNotMet"]>>;
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"]>>
declare function sendForgotPasswordEmail(email: string): Promise<Result<undefined, KnownErrors["UserNotFound"]>>;
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"]>>
declare function sendMagicLinkEmail(email: string): Promise<Result<{ nonce: string }, KnownErrors["RedirectUrlNotWhitelisted"]>>;
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:
options
objectAn object containing multiple properties.
Show Parameters
tokenStore
unionrequiredShow possible values
"nextjs-cookie"
string"cookie"
string{ accessToken: string, refreshToken: string }
objectRequest
objectbaseUrl
stringprojectId
stringpublishableClientKey
stringsecretServerKey
stringThe 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
objectShow properties
home
stringsignIn
stringafterSignIn
stringsignUp
stringafterSignUp
stringafterSignOut
stringemailVerification
stringpasswordReset
stringforgotPassword
stringaccountSettings
stringhandler
stringnoAutomaticPrefetch
booleandeclare new(options: {
tokenStore: "nextjs-cookie" | "cookie" | { accessToken: string, refreshToken: string } | Request;
baseUrl?: string;
projectId?: string;
publishableClientKey?: string;
urls: {
...
};
noAutomaticPrefetch?: boolean;
}): StackServerApp;
const stackServerApp = new StackServerApp({
tokenStore: "nextjs-cookie",
urls: {
signIn: '/my-custom-sign-in-page',
},
});
Enhanced version of StackClientApp.getUser()
with server permissions.
Overloads:
getUser(id: string): Promise<ServerUser | null>
- Get user by IDgetUser(options?: { or?: "return-null" | "redirect" | "throw" }): Promise<CurrentServerUser | null>
- Get current user
// 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>;
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:
options
objectAn object containing multiple properties.
Show options properties
cursor
stringThe cursor to start the result set from.
limit
numberThe 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
booleanWhether to sort the results in descending order.
query
stringA 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 }>
declare function listUsers(options?: {
cursor?: string;
limit?: number;
orderBy?: "signedUpAt";
desc?: boolean;
query?: string;
}): Promise<ServerUser[] & { nextCursor: string | null }>;
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.
Creates a new user from the server.
Parameters:
options?
(object)primaryEmail?
(string) - User's primary emailprimaryEmailVerified?
(boolean) - Whether email is verifiedprimaryEmailAuthEnabled?
(boolean) - Whether email auth is enabledpassword?
(string) - User's passwordotpAuthEnabled?
(boolean) - Enable OTP/magic link authdisplayName?
(string) - User's display name
Returns: Promise<ServerUser>
declare function createUser(options?: {
primaryEmail?: string;
primaryEmailVerified?: boolean;
primaryEmailAuthEnabled?: boolean;
password?: string;
otpAuthEnabled?: boolean;
displayName?: string;
}): Promise<ServerUser>;
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>
declare function getTeam(id: string): Promise<ServerTeam | null>;
const team = await stackServerApp.getTeam("team_id_123");
Functionally equivalent to getTeam(id)
, but as a React hook.
Lists all teams on the current project.
Returns: Promise<ServerTeam[]>
declare function listTeams(): Promise<ServerTeam[]>;
const teams = await stackServerApp.listTeams();
console.log(teams);
Functionally equivalent to listTeams()
, but as a React hook.
Creates a team without adding a user to it.
Parameters:
data
(object)displayName
(string) - Team display nameprofileImageUrl?
(string | null) - Team profile image URL
Returns: Promise<ServerTeam>
declare function createTeam(data: {
displayName: string;
profileImageUrl?: string | null;
}): Promise<ServerTeam>;
const team = await stackServerApp.createTeam({
displayName: "New Team",
profileImageUrl: "https://example.com/profile.jpg",
});