wasp/client/auth
Client-side auth APIs: getting the logged-in user, logging out, the generated Auth UI components, and the functions and helpers for building your own auth UI.
Only available if your app has auth enabled. Some exports depend on the auth methods your app enables:
- With Email auth: the email versions of login and signup, and requestPasswordReset, resetPassword, verifyEmail, ForgotPasswordForm, ResetPasswordForm, and VerifyEmailForm.
- With Username & password auth: the username versions of login and signup.
- With a social auth provider: that provider's sign-in URL and button, e.g. googleSignInUrl and GoogleSignInButton for Google.
login, signup, verifyEmail,
requestPasswordReset, and resetPassword reject with a
WaspHttpError if the server responds
with an error, instead of resolving with success: false.
Type Aliases
CustomizationOptions
CustomizationOptions =
object
Props you can pass to all the Auth UI forms to customize their look:
appearance: customizes the form's colors and font sizes. The Auth UI uses CSS variables in its styling, and you can override the default theme tokens by setting them inappearance.colors(e.g.brand,brandAccent,submitButtonText) andappearance.fontSizes.logo: the path to your logo, which the form shows at the top.socialLayout: the layout of the social login buttons, which can be"horizontal"(the default) or"vertical".
Example
We recommend defining your appearance in a separate file and importing it into your components:
// src/appearance.ts
import type { CustomizationOptions } from "wasp/client/auth";
export const authAppearance: CustomizationOptions["appearance"] = {
colors: {
brand: "#5969b8", // blue
brandAccent: "#de5998", // pink
submitButtonText: "white",
},
};
// src/LoginPage.tsx
import { LoginForm } from "wasp/client/auth";
import { authAppearance } from "./appearance";
import todoLogo from "./todoLogo.png";
export function LoginPage() {
return (
<LoginForm
appearance={authAppearance}
logo={todoLogo}
socialLayout="vertical"
/>
);
}
See
Properties
appearance?
optionalappearance?:object
colors?
optionalcolors?:object
colors.brand?
optionalbrand?:string
colors.brandAccent?
optionalbrandAccent?:string
colors.darkRed?
optionaldarkRed?:string
colors.errorBackground?
optionalerrorBackground?:string
colors.errorText?
optionalerrorText?:string
colors.formErrorText?
optionalformErrorText?:string
colors.gray400?
optionalgray400?:string
colors.gray500?
optionalgray500?:string
colors.gray600?
optionalgray600?:string
colors.gray700?
optionalgray700?:string
colors.green?
optionalgreen?:string
colors.red?
optionalred?:string
colors.submitButtonText?
optionalsubmitButtonText?:string
colors.successBackground?
optionalsuccessBackground?:string
colors.successText?
optionalsuccessText?:string
colors.waspYellow?
optionalwaspYellow?:string
fontSizes?
optionalfontSizes?:object
fontSizes.sm?
optionalsm?:string
logo?
optionallogo?:string
socialLayout?
optionalsocialLayout?:"horizontal"|"vertical"
Variables
discordSignInUrl
constdiscordSignInUrl:string
The URL that starts the Discord
login flow. Use it as a link's href to build your own sign-in button.
Only available with Discord auth.
See
Create your own UI for social auth
getMe
The Query that useAuth uses to fetch the logged-in user.
You can call it directly, or pass it to
useQuery.
It resolves to null if the user isn't logged in.
githubSignInUrl
constgithubSignInUrl:string
The URL that starts the GitHub
login flow. Use it as a link's href to build your own sign-in button.
Only available with GitHub auth.
See
Create your own UI for social auth
googleSignInUrl
constgoogleSignInUrl:string
The URL that starts the Google
login flow. Use it as a link's href to build your own sign-in button.
Only available with Google auth.
Example
import { googleSignInUrl } from "wasp/client/auth";
export const LoginPage = () => {
return <a href={googleSignInUrl}>Sign in with Google</a>;
};
See
Create your own UI for social auth
keycloakSignInUrl
constkeycloakSignInUrl:string
The URL that starts the Keycloak
login flow. Use it as a link's href to build your own sign-in button.
Only available with Keycloak auth.
See
Create your own UI for social auth
microsoftSignInUrl
constmicrosoftSignInUrl:string
The URL that starts the Microsoft
login flow. Use it as a link's href to build your own sign-in button.
Only available with Microsoft auth.
See
Create your own UI for social auth
slackSignInUrl
constslackSignInUrl:string
The URL that starts the Slack
login flow. Use it as a link's href to build your own sign-in button.
Only available with Slack auth.
See
Create your own UI for social auth
Functions
login()
Call Signature
login(
data):Promise<void>
Logs the user in with Email auth.
Only available with Email auth. Make sure to redirect the user on success (e.g. to the main page of the app).
Parameters
data
The user's credentials.
email
string
The user's email.
password
string
The user's password.
Returns
Promise<void>
Example
import { login } from "wasp/client/auth";
try {
await login({ email: email.trim(), password });
navigate("/");
} catch (error) {
setError(error);
}
See
Create your own UI for email auth
Call Signature
login(
data):Promise<void>
Logs the user in with Username & password auth.
Only available with Username & password auth. Make sure to redirect the user on success (e.g. to the main page of the app).
Parameters
data
The user's credentials.
password
string
The user's password.
username
string
The user's username.
Returns
Promise<void>
Example
import { login } from "wasp/client/auth";
try {
await login({ username, password });
navigate("/");
} catch (error) {
setError(error);
}
See
Create your own UI for username and password auth
logout()
logout():
Promise<void>
Logs the user out.
It deletes the session from the server and the user's data from the client, and clears the cache of all Queries. It removes the local data even if the request to the server fails, though the returned Promise still rejects.
Returns
Promise<void>
Example
import { logout } from "wasp/client/auth";
const LogoutButton = () => {
return <button onClick={logout}>Logout</button>;
};
See
requestPasswordReset()
requestPasswordReset(
data):Promise<{success:boolean; }>
Sends the user a password reset email. It doesn't reset their password.
Only available with Email auth.
Parameters
data
The password reset request.
Returns
Promise<{ success: boolean; }>
Example
import { requestPasswordReset } from "wasp/client/auth";
await requestPasswordReset({ email: email.trim() });
See
Create your own UI for email auth
resetPassword()
resetPassword(
data):Promise<{success:boolean; }>
Confirms a password reset and sets the user's new password.
Only available with Email auth. Make sure to redirect the user on success (e.g. to the login page).
Parameters
data
The password reset data.
password
string
The user's new password.
token
string
The token Wasp created when the user requested the
password reset. Wasp puts it in the token query parameter of the link in
the password reset email.
Returns
Promise<{ success: boolean; }>
Example
import { resetPassword } from "wasp/client/auth";
const token = new URLSearchParams(location.search).get("token");
if (!token) throw new Error("Token not found in URL");
await resetPassword({ token, password });
navigate("/login");
See
Create your own UI for email auth
signup()
Call Signature
signup(
data):Promise<{success:boolean; }>
Signs the user up with Email auth, and sends them the verification email.
Only available with Email auth. It doesn't log the user in, since they still need to verify their email.
By default, Wasp only saves the email and password fields. If you
define extra signup fields,
pass them in data too.
Parameters
data
object & UserEmailSignupFields
The new user's data: email and password (both required), plus
your extra signup fields.
Returns
Promise<{ success: boolean; }>
Example
import { signup } from "wasp/client/auth";
try {
await signup({ email: email.trim(), password });
setNeedsConfirmation(true);
} catch (error) {
setError(error);
}
See
Create your own UI for email auth
Call Signature
signup(
data):Promise<void>
Signs the user up with Username & password auth.
Only available with Username & password auth. It doesn't log the user in: call login after it.
By default, Wasp only saves the username and password fields. If you
define extra signup fields,
pass them in data too.
Parameters
data
object & UserUsernameAndPasswordSignupFields
The new user's data: username and password (both required),
plus your extra signup fields.
Returns
Promise<void>
Example
import { login, signup } from "wasp/client/auth";
try {
await signup({ username, password });
await login({ username, password });
navigate("/");
} catch (error) {
setError(error);
}
See
Create your own UI for username and password auth
useAuth()
useAuth():
UseQueryResult<AuthUser|null>
Gets the logged-in user from a React component, and keeps it up to date.
It's a thin wrapper over the useQuery hook (calling the getMe Query), and returns data in the same format.
You can use it in any page. In pages with authRequired, you can use the
user prop instead.
Returns
UseQueryResult<AuthUser | null>
react-query's result object, whose data is the logged-in
AuthUser, null if the user isn't logged in, or undefined until
the Query first loads.
Example
import { useAuth, logout } from "wasp/client/auth";
import { Link } from "react-router";
import Todo from "../Todo";
export function Main() {
const { data: user } = useAuth();
if (!user) {
return (
<span>
Please <Link to="/login">login</Link> or{" "}
<Link to="/signup">sign up</Link>.
</span>
);
} else {
return (
<>
<button onClick={logout}>Logout</button>
<Todo />
</>
);
}
}
See
Getting the user in non-authenticated routes
verifyEmail()
verifyEmail(
data):Promise<{reason?:string;success:boolean; }>
Marks the user's email as verified and their account as active.
Only available with Email auth. Make sure to redirect the user on success (e.g. to the login page).
Parameters
data
The verification data.
token
string
The token Wasp created when the user signed up. Wasp puts
it in the token query parameter of the link in the verification email.
Returns
Promise<{ reason?: string; success: boolean; }>
Example
import { verifyEmail } from "wasp/client/auth";
const token = new URLSearchParams(location.search).get("token");
if (!token) throw new Error("Token not found in URL");
await verifyEmail({ token });
navigate("/login");
See
Create your own UI for email auth
Components
<FormError>
constFormError:React.ForwardRefExoticComponent<Omit<React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>,HTMLDivElement>,"ref"> &React.RefAttributes<HTMLDivElement>>
A form field error message, styled like the rest of the Auth UI. Use it to build the extra fields you pass to SignupForm.
See
<FormInput>
constFormInput:React.ForwardRefExoticComponent<Omit<React.DetailedHTMLProps<React.InputHTMLAttributes<HTMLInputElement>,HTMLInputElement>,"ref"> &React.RefAttributes<HTMLInputElement>>
A text input, styled like the rest of the Auth UI. Use it to build the extra fields you pass to SignupForm.
See
<FormItemGroup>
constFormItemGroup:React.ForwardRefExoticComponent<Omit<React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>,HTMLDivElement>,"ref"> &React.RefAttributes<HTMLDivElement>>
A wrapper for a form field, which groups its label, input, and error. Use it to build the extra fields you pass to SignupForm, so they look like the rest of the form.
See
<FormLabel>
constFormLabel:React.ForwardRefExoticComponent<Omit<React.DetailedHTMLProps<React.LabelHTMLAttributes<HTMLLabelElement>,HTMLLabelElement>,"ref"> &React.RefAttributes<HTMLLabelElement>>
A form field label, styled like the rest of the Auth UI. Use it to build the extra fields you pass to SignupForm.
See
<FormPasswordInput>
constFormPasswordInput:React.ForwardRefExoticComponent<Omit<Omit<React.DetailedHTMLProps<React.InputHTMLAttributes<HTMLInputElement>,HTMLInputElement>,"ref">,"type"> &React.RefAttributes<HTMLInputElement>>
A password input with a button that shows or hides the password, styled like
the rest of the Auth UI. It takes the same props as an <input>, except
type. Use it to build the extra fields you pass to SignupForm.
See
<FormTextarea>
constFormTextarea:React.ForwardRefExoticComponent<Omit<React.DetailedHTMLProps<React.TextareaHTMLAttributes<HTMLTextAreaElement>,HTMLTextAreaElement>,"ref"> &React.RefAttributes<HTMLTextAreaElement>>
A textarea, styled like the rest of the Auth UI. Use it to build the extra fields you pass to SignupForm.
See
<DiscordSignInButton>
DiscordSignInButton():
Element
A button that starts the Discord login flow, styled like the Auth UI's.
Only available with Discord auth.
Returns
Element
See
Create your own UI for social auth
<ForgotPasswordForm>
ForgotPasswordForm(
props):Element
A form where users who forgot their password can request a password reset email.
Only available with Email auth.
Parameters
props
Options to customize the form's look.
Returns
Element
Example
import { ForgotPasswordForm } from "wasp/client/auth";
export function ForgotPasswordPage() {
return <ForgotPasswordForm />;
}
See
<GitHubSignInButton>
GitHubSignInButton():
Element
A button that starts the GitHub login flow, styled like the Auth UI's.
Only available with GitHub auth.
Returns
Element
See
Create your own UI for social auth
<GoogleSignInButton>
GoogleSignInButton():
Element
A button that starts the Google login flow, styled like the Auth UI's.
Only available with Google auth.
Returns
Element
Example
import { GoogleSignInButton } from "wasp/client/auth";
export const LoginPage = () => {
return <GoogleSignInButton />;
};
See
Create your own UI for social auth
<KeycloakSignInButton>
KeycloakSignInButton():
Element
A button that starts the Keycloak login flow, styled like the Auth UI's.
Only available with Keycloak auth.
Returns
Element
See
Create your own UI for social auth
<LoginForm>
LoginForm(
props):Element
A login form, which shows the login fields and buttons of all the auth methods your app enables.
Parameters
props
Options to customize the form's look.
Returns
Element
Example
import { LoginForm } from "wasp/client/auth";
export function LoginPage() {
return <LoginForm />;
}
See
<MicrosoftSignInButton>
MicrosoftSignInButton():
Element
A button that starts the Microsoft login flow, styled like the Auth UI's.
Only available with Microsoft auth.
Returns
Element
See
Create your own UI for social auth
<ResetPasswordForm>
ResetPasswordForm(
props):Element
A form where users set a new password, after following the link in the password reset email.
Only available with Email
auth. Render it in the page of the route you set as
auth.methods.email.passwordReset.clientRoute.
Parameters
props
Options to customize the form's look.
Returns
Element
Example
import { ResetPasswordForm } from "wasp/client/auth";
export function ResetPasswordPage() {
return <ResetPasswordForm />;
}
See
<SignupForm>
SignupForm(
props):Element
A signup form, which shows the signup fields and buttons of all the auth methods your app enables.
Parameters
props
CustomizationOptions & object
Options to customize the form's look, and:
-
additionalFields: extra fields or UI to add to the form, e.g. for extra signup fields. It can be either a list of extra fields or a render function, and only has an effect with Email or Username & password auth.The list's items can be objects or render functions (you can combine them). Wasp adds them to the form one by one, in the order you pass them in:
-
Objects are a simple way to describe new fields you need, but a bit less flexible than render functions. They have the following properties:
name(required): the name of the field.label(required): the label of the field (used in the UI).type(required): the type of the field, which can be"input"or"textarea".validations: an object with the validation rules for the field, which Wasp passes toreact-hook-form'sregisterfunction (e.g.{ required: "Address is required" }). Read more about the available validation rules in the react-hook-form docs.
-
Render functions can render any UI you want, but they require a bit more code. They receive two arguments and return a React node:
form: thereact-hook-formobject (read more about it in the react-hook-form docs). Use itsform.registerfunction to register your fields.state: the form state object, which has anisLoading: booleanproperty that tells whether the form is currently submitting.
If you pass a single render function instead of a list, Wasp renders whatever it returns below the default fields.
-
Returns
Element
Examples
Adding a field with an object and another with a render function:
import {
SignupForm,
FormError,
FormInput,
FormItemGroup,
FormLabel,
} from "wasp/client/auth";
export const SignupPage = () => {
return (
<SignupForm
additionalFields={[
{
name: "address",
label: "Address",
type: "input",
validations: {
required: "Address is required",
},
},
(form, state) => {
return (
<FormItemGroup>
<FormLabel>Phone Number</FormLabel>
<FormInput
{...form.register("phoneNumber", {
required: "Phone number is required",
})}
disabled={state.isLoading}
/>
{form.formState.errors.phoneNumber && (
<FormError>
{form.formState.errors.phoneNumber.message}
</FormError>
)}
</FormItemGroup>
);
},
]}
/>
);
};
Adding UI with a single render function:
import { SignupForm, FormItemGroup } from "wasp/client/auth";
export const SignupPage = () => {
return (
<SignupForm
additionalFields={(form, state) => {
const username = form.watch("username");
return (
username && (
<FormItemGroup>
Hello there <strong>{username}</strong>
</FormItemGroup>
)
);
}}
/>
);
};
See
<SlackSignInButton>
SlackSignInButton():
Element
A button that starts the Slack login flow, styled like the Auth UI's.
Only available with Slack auth.
Returns
Element
See
Create your own UI for social auth
<VerifyEmailForm>
VerifyEmailForm(
props):Element
A form that verifies the user's email, after they follow the link in the verification email they receive when they sign up.
Only available with Email
auth. Render it in the page of the route you set as
auth.methods.email.emailVerification.clientRoute.
Parameters
props
Options to customize the form's look.
Returns
Element
Example
import { VerifyEmailForm } from "wasp/client/auth";
export function VerifyEmailPage() {
return <VerifyEmailForm />;
}
See
Referenced Types
AdditionalSignupField
AdditionalSignupField =
object
Properties
label
label:
string
name
name:
string
type
type:
"input"|"textarea"
validations?
optionalvalidations?:RegisterOptions<LoginSignupFormFields>
AdditionalSignupFieldRenderFn
AdditionalSignupFieldRenderFn = (
hookForm,formState) =>React.ReactNode
Parameters
hookForm
UseFormReturn<LoginSignupFormFields>
formState
Returns
React.ReactNode
AdditionalSignupFields
AdditionalSignupFields = (
AdditionalSignupField|AdditionalSignupFieldRenderFn)[] |AdditionalSignupFieldRenderFn
ClientOperation
ClientOperation<
Input,Output> =IfAny<Input, (args?) =>Promise<Output>,ClientOperationWithNonAnyInput<Input,Output>>
Type Parameters
Input
Input
Output
Output
ClientOperationWithNonAnyInput
ClientOperationWithNonAnyInput<
Input,Output> = [Input] extends [never] ? (args?) =>Promise<Output> : [Input] extends [void] ? () =>Promise<Output> : (args) =>Promise<Output>
Type Parameters
Input
Input
Output
Output
FormState
FormState =
object
Properties
isLoading
isLoading:
boolean
IfAny
IfAny<
Value,Then,Else> =0extends1&Value?Then:Else
Type Parameters
Value
Value
Then
Then
Else
Else
LoginSignupFormFields
LoginSignupFormFields =
object
The raw values of the form's inputs, including the ones users add through
additionalFields.
Index Signature
[key: string]: string
Query
Query<
Input,Output> =QueryFunction<Input,Output> &QueryMetadata
The client Query object type. It's a callable Query function with some extra properties (metadata).
Type Parameters
Input
Input
Output
Output
QueryFunction
QueryFunction<
Input,Output> =ClientOperation<Input,Output>
The client Query function type.
Type Parameters
Input
Input
Output
Output
QueryMetadata
QueryMetadata =
object
All extra properties (metadata) found on a Query object type.
Properties
queryCacheKey
queryCacheKey:
string[]
route
route:
Route