2023-08-11 17:47:49 +03:00
---
2024-01-15 13:00:54 +03:00
title: Overview
2023-08-11 17:47:49 +03:00
---
import { AuthMethodsGrid } from "@site/src/components/AuthMethodsGrid";
2024-01-15 13:00:54 +03:00
import { Required } from '@site/src/components/Tag';
import ReadMoreAboutAuthEntities from './\_read-more-about-auth-entities.md';
2023-08-11 17:47:49 +03:00
2024-01-15 13:00:54 +03:00
Auth is an essential piece of any serious application. That's why Wasp provides authentication and authorization support out of the box.
2023-12-13 19:52:55 +03:00
Here's a 1-minute tour of how full-stack auth works in Wasp:
< div className = 'video-container' >
< iframe src = "https://www.youtube.com/embed/Qiro77q-ulI?si=y8Rejsbjb1HJC6FA" frameborder = "1" allow = "accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen > < / iframe >
< / div >
2023-08-11 17:47:49 +03:00
2024-01-18 19:19:06 +03:00
Enabling auth for your app is optional and can be done by configuring the `auth` field of your `app` declaration:
2023-08-11 17:47:49 +03:00
< Tabs groupId = "js-ts" >
< TabItem value = "js" label = "JavaScript" >
```wasp title="main.wasp"
app MyApp {
title: "My app",
//...
auth: {
userEntity: User,
methods: {
usernameAndPassword: {}, // use this or email, not both
email: {}, // use this or usernameAndPassword, not both
google: {},
gitHub: {},
},
onAuthFailedRedirectTo: "/someRoute"
}
}
//...
```
2023-09-12 14:19:47 +03:00
2023-08-11 17:47:49 +03:00
< / TabItem >
< TabItem value = "ts" label = "TypeScript" >
```wasp title="main.wasp"
app MyApp {
title: "My app",
//...
auth: {
userEntity: User,
methods: {
usernameAndPassword: {}, // use this or email, not both
email: {}, // use this or usernameAndPassword, not both
google: {},
gitHub: {},
},
onAuthFailedRedirectTo: "/someRoute"
}
}
//...
```
2023-09-12 14:19:47 +03:00
2023-08-11 17:47:49 +03:00
< / TabItem >
< / Tabs >
< small >
2023-09-12 14:19:47 +03:00
Read more about the `auth` field options in the [API Reference ](#api-reference ) section.
2023-08-11 17:47:49 +03:00
< / small >
We will provide a quick overview of auth in Wasp and link to more detailed documentation for each auth method.
## Available auth methods
Wasp supports the following auth methods:
< AuthMethodsGrid / >
2024-01-12 19:42:53 +03:00
Let's say we enabled the [Username & password ](../auth/username-and-pass ) authentication.
2023-08-11 17:47:49 +03:00
2024-01-12 19:42:53 +03:00
We get an auth backend with signup and login endpoints. We also get the `user` object in our [Operations ](../data-model/operations/overview ) and we can decide what to do based on whether the user is logged in or not.
2023-08-11 17:47:49 +03:00
2024-01-12 19:42:53 +03:00
We would also get the [Auth UI ](../auth/ui ) generated for us. We can set up our login and signup pages where our users can **create their account** and **login** . We can then protect certain pages by setting `authRequired: true` for them. This will make sure that only logged-in users can access them.
2023-08-11 17:47:49 +03:00
We will also have access to the `user` object in our frontend code, so we can show different UI to logged-in and logged-out users. For example, we can show the user's name in the header alongside a **logout button** or a login button if the user is not logged in.
## Protecting a page with `authRequired`
When declaring a page, you can set the `authRequired` property.
If you set it to `true` , only authenticated users can access the page. Unauthenticated users are redirected to a route defined by the `app.auth.onAuthFailedRedirectTo` field.
< Tabs groupId = "js-ts" >
< TabItem value = "js" label = "JavaScript" >
```wasp title="main.wasp"
page MainPage {
2024-02-23 15:07:28 +03:00
component: import Main from "@src/pages/Main",
2023-08-11 17:47:49 +03:00
authRequired: true
}
```
2023-09-12 14:19:47 +03:00
2023-08-11 17:47:49 +03:00
< / TabItem >
< TabItem value = "ts" label = "TypeScript" >
```wasp title="main.wasp"
page MainPage {
2024-02-23 15:07:28 +03:00
component: import Main from "@src/pages/Main",
2023-08-11 17:47:49 +03:00
authRequired: true
}
```
2023-09-12 14:19:47 +03:00
2023-08-11 17:47:49 +03:00
< / TabItem >
< / Tabs >
:::caution Requires auth method
You can only use `authRequired` if your app uses one of the [available auth methods ](#available-auth-methods ).
:::
If `authRequired` is set to `true` , the page's React component (specified by the `component` property) receives the `user` object as a prop. Read more about the `user` object in the [Accessing the logged-in user section ](#accessing-the-logged-in-user ).
## Logout action
We provide an action for logging out the user. Here's how you can use it:
< Tabs groupId = "js-ts" >
< TabItem value = "js" label = "JavaScript" >
2024-02-23 15:03:43 +03:00
```jsx title="src/components/LogoutButton.jsx"
import { logout } from 'wasp/client/auth'
2023-08-11 17:47:49 +03:00
const LogoutButton = () => {
2023-09-12 14:19:47 +03:00
return < button onClick = {logout} > Logout< / button >
2023-08-11 17:47:49 +03:00
}
```
2023-09-12 14:19:47 +03:00
2023-08-11 17:47:49 +03:00
< / TabItem >
< TabItem value = "ts" label = "TypeScript" >
2024-02-23 15:03:43 +03:00
```tsx title="src/components/LogoutButton.tsx"
import { logout } from 'wasp/client/auth'
2023-08-11 17:47:49 +03:00
const LogoutButton = () => {
2023-09-12 14:19:47 +03:00
return < button onClick = {logout} > Logout< / button >
2023-08-11 17:47:49 +03:00
}
```
2023-09-12 14:19:47 +03:00
2023-08-11 17:47:49 +03:00
< / TabItem >
< / Tabs >
## Accessing the logged-in user
2024-01-15 13:00:54 +03:00
You can get access to the `user` object both on the server and on the client. The `user` object contains the logged-in user's data.
The `user` object has all the fields that you defined in your `User` entity, plus the `auth` field which contains the auth identities connected to the user. For example, if the user signed up with their email, the `user` object might look something like this:
```js
const user = {
id: "19c7d164-b5cb-4dde-a0cc-0daea77cf854",
// Your entity's fields.
address: "My address",
// ...
// Auth identities connected to the user.
auth: {
id: "26ab6f96-ed76-4ee5-9ac3-2fd0bf19711f",
identities: [
{
providerName: "email",
providerUserId: "some@email.com",
providerData: { ... },
},
]
},
}
```
< ReadMoreAboutAuthEntities / >
2023-08-11 17:47:49 +03:00
### On the client
There are two ways to access the `user` object on the client:
2023-09-12 14:19:47 +03:00
- the `user` prop
2023-08-11 17:47:49 +03:00
- the `useAuth` hook
#### Using the `user` prop
If the page's declaration sets `authRequired` to `true` , the page's React component receives the `user` object as a prop:
< Tabs groupId = "js-ts" >
< TabItem value = "js" label = "JavaScript" >
```wasp title="main.wasp"
// ...
page AccountPage {
2024-02-23 15:07:28 +03:00
component: import Account from "@src/pages/Account",
2023-08-11 17:47:49 +03:00
authRequired: true
}
```
2024-02-23 15:03:43 +03:00
```jsx title="src/pages/Account.jsx"
2023-09-12 14:19:47 +03:00
import Button from './Button'
2024-02-23 15:03:43 +03:00
import { logout } from 'wasp/client/auth'
2023-08-11 17:47:49 +03:00
const AccountPage = ({ user }) => {
return (
< div >
< Button onClick = {logout} > Logout< / Button >
{JSON.stringify(user, null, 2)}
< / div >
2023-09-12 14:19:47 +03:00
)
}
2023-08-11 17:47:49 +03:00
2023-09-12 14:19:47 +03:00
export default AccountPage
2023-08-11 17:47:49 +03:00
```
2023-09-12 14:19:47 +03:00
2023-08-11 17:47:49 +03:00
< / TabItem >
< TabItem value = "ts" label = "TypeScript" >
```wasp title="main.wasp"
// ...
page AccountPage {
2024-02-23 15:07:28 +03:00
component: import Account from "@src/pages/Account",
2023-08-11 17:47:49 +03:00
authRequired: true
}
```
2024-02-23 15:03:43 +03:00
```tsx title="src/pages/Account.tsx"
import { type AuthUser } from 'wasp/auth'
2023-09-12 14:19:47 +03:00
import Button from './Button'
2024-02-23 15:03:43 +03:00
import { logout } from 'wasp/client/auth'
2023-08-11 17:47:49 +03:00
2024-02-23 15:03:43 +03:00
const AccountPage = ({ user }: { user: AuthUser }) => {
2023-08-11 17:47:49 +03:00
return (
< div >
< Button onClick = {logout} > Logout< / Button >
{JSON.stringify(user, null, 2)}
< / div >
2023-09-12 14:19:47 +03:00
)
}
2023-08-11 17:47:49 +03:00
2023-09-12 14:19:47 +03:00
export default AccountPage
2023-08-11 17:47:49 +03:00
```
2023-09-12 14:19:47 +03:00
2023-08-11 17:47:49 +03:00
< / TabItem >
< / Tabs >
#### Using the `useAuth` hook
Wasp provides a React hook you can use in the client components - `useAuth` .
This hook is a thin wrapper over Wasp's `useQuery` hook and returns data in the same format.
< Tabs groupId = "js-ts" >
< TabItem value = "js" label = "JavaScript" >
2024-02-23 15:03:43 +03:00
```jsx title="src/pages/MainPage.jsx"
import { useAuth, logout } from 'wasp/client/auth'
2023-08-11 17:47:49 +03:00
import { Link } from 'react-router-dom'
import Todo from '../Todo'
export function Main() {
const { data: user } = useAuth()
if (!user) {
return (
< span >
2023-09-12 14:19:47 +03:00
Please < Link to = "/login" > login< / Link > or{' '}
< Link to = "/signup" > sign up< / Link > .
2023-08-11 17:47:49 +03:00
< / span >
)
} else {
return (
< >
< button onClick = {logout} > Logout< / button >
< Todo / >
2023-09-12 14:19:47 +03:00
< />
2023-08-11 17:47:49 +03:00
)
}
}
```
2023-09-12 14:19:47 +03:00
2023-08-11 17:47:49 +03:00
< / TabItem >
< TabItem value = "ts" label = "TypeScript" >
2024-02-23 15:03:43 +03:00
```tsx title="src/pages/MainPage.tsx"
import { useAuth, logout } from 'wasp/client/auth'
2023-08-11 17:47:49 +03:00
import { Link } from 'react-router-dom'
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 / >
< />
)
}
}
```
2023-09-12 14:19:47 +03:00
2023-08-11 17:47:49 +03:00
< / TabItem >
< / Tabs >
:::tip
Since the `user` prop is only available in a page's React component: use the `user` prop in the page's React component and the `useAuth` hook in any other React component.
:::
### On the server
#### Using the `context.user` object
2024-01-15 13:00:54 +03:00
When authentication is enabled, all [queries and actions ](../data-model/operations/overview ) have access to the `user` object through the `context` argument. `context.user` contains all User entity's fields and the auth identities connected to the user. We strip out the `hashedPassword` field from the identities for security reasons.
2023-08-11 17:47:49 +03:00
< Tabs groupId = "js-ts" >
< TabItem value = "js" label = "JavaScript" >
2024-02-23 15:03:43 +03:00
```js title="src/actions.js"
import { HttpError } from 'wasp/server'
2023-08-11 17:47:49 +03:00
export const createTask = async (task, context) => {
if (!context.user) {
throw new HttpError(403)
}
const Task = context.entities.Task
return Task.create({
data: {
description: task.description,
user: {
2023-09-12 14:19:47 +03:00
connect: { id: context.user.id },
},
},
2023-08-11 17:47:49 +03:00
})
}
```
2023-09-12 14:19:47 +03:00
2023-08-11 17:47:49 +03:00
< / TabItem >
< TabItem value = "ts" label = "TypeScript" >
2024-02-23 15:03:43 +03:00
```ts title="src/actions.ts"
import { type Task } from 'wasp/entities'
import { type CreateTask } from 'wasp/server/operations'
import { HttpError } from 'wasp/server'
2023-08-11 17:47:49 +03:00
2023-09-12 14:19:47 +03:00
type CreateTaskPayload = Pick< Task , ' description ' >
2023-08-11 17:47:49 +03:00
2023-09-12 14:19:47 +03:00
export const createTask: CreateTask< CreateTaskPayload , Task > = async (
args,
context
) => {
2023-08-11 17:47:49 +03:00
if (!context.user) {
throw new HttpError(403)
}
const Task = context.entities.Task
return Task.create({
data: {
description: args.description,
user: {
2023-09-12 14:19:47 +03:00
connect: { id: context.user.id },
},
},
2023-08-11 17:47:49 +03:00
})
}
```
2023-09-12 14:19:47 +03:00
2023-08-11 17:47:49 +03:00
< / TabItem >
< / Tabs >
To implement access control in your app, each operation must check `context.user` and decide what to do. For example, if `context.user` is `undefined` inside a private operation, the user's access should be denied.
2024-01-12 19:42:53 +03:00
When using WebSockets, the `user` object is also available on the `socket.data` object. Read more in the [WebSockets section ](../advanced/web-sockets#websocketfn-function ).
2023-08-11 17:47:49 +03:00
2024-01-18 19:19:06 +03:00
## Sessions
Wasp's auth uses sessions to keep track of the logged-in user. The session is stored in `localStorage` on the client and in the database on the server. Under the hood, Wasp uses the excellent [Lucia Auth v3 ](https://v3.lucia-auth.com/ ) library for session management.
When users log in, Wasp creates a session for them and stores it in the database. The session is then sent to the client and stored in `localStorage` . When users log out, Wasp deletes the session from the database and from `localStorage` .
2024-01-15 13:00:54 +03:00
## User Entity
### Password Hashing
If you are saving a user's password in the database, you should **never** save it as plain text. You can use Wasp's helper functions for serializing and deserializing provider data which will automatically hash the password for you:
2023-08-11 17:47:49 +03:00
2024-01-15 13:00:54 +03:00
```wasp title="main.wasp"
// ...
2023-08-11 17:47:49 +03:00
2024-01-15 13:00:54 +03:00
action updatePassword {
2024-02-23 15:03:43 +03:00
fn: import { updatePassword } from "@src/auth",
2024-01-15 13:00:54 +03:00
}
```
2023-08-11 17:47:49 +03:00
< Tabs groupId = "js-ts" >
< TabItem value = "js" label = "JavaScript" >
2024-02-23 15:03:43 +03:00
```js title="src/auth.js"
2024-01-15 13:00:54 +03:00
import {
2024-02-23 15:07:28 +03:00
createProviderId,
findAuthIdentity,
updateAuthIdentityProviderData,
deserializeAndSanitizeProviderData,
2024-02-23 15:03:43 +03:00
} from 'wasp/server/auth';
2024-01-15 13:00:54 +03:00
2023-08-11 17:47:49 +03:00
export const updatePassword = async (args, context) => {
2024-01-15 13:00:54 +03:00
const providerId = createProviderId('email', args.email)
const authIdentity = await findAuthIdentity(providerId)
if (!authIdentity) {
throw new HttpError(400, "Unknown user")
}
const providerData = deserializeAndSanitizeProviderData(authIdentity.providerData)
// Updates the password and hashes it automatically.
await updateAuthIdentityProviderData(providerId, providerData, {
hashedPassword: args.password,
2023-08-11 17:47:49 +03:00
})
}
```
2023-09-12 14:19:47 +03:00
2023-08-11 17:47:49 +03:00
< / TabItem >
< TabItem value = "ts" label = "TypeScript" >
2024-02-23 15:03:43 +03:00
```ts title="src/auth.ts"
2024-01-15 13:00:54 +03:00
import {
2024-02-23 15:07:28 +03:00
createProviderId,
findAuthIdentity,
updateAuthIdentityProviderData,
deserializeAndSanitizeProviderData,
2024-02-23 15:03:43 +03:00
} from 'wasp/server/auth';
import { type UpdatePassword } from 'wasp/server/operations'
2023-08-11 17:47:49 +03:00
2023-09-12 14:19:47 +03:00
export const updatePassword: UpdatePassword<
2024-01-15 13:00:54 +03:00
{ email: string; password: string },
void,
2023-09-12 14:19:47 +03:00
> = async (args, context) => {
2024-01-15 13:00:54 +03:00
const providerId = createProviderId('email', args.email)
const authIdentity = await findAuthIdentity(providerId)
if (!authIdentity) {
throw new HttpError(400, "Unknown user")
}
const providerData = deserializeAndSanitizeProviderData< 'email'>(authIdentity.providerData)
// Updates the password and hashes it automatically.
await updateAuthIdentityProviderData(providerId, providerData, {
hashedPassword: args.password,
2023-08-11 17:47:49 +03:00
})
}
```
2023-09-12 14:19:47 +03:00
2023-08-11 17:47:49 +03:00
< / TabItem >
< / Tabs >
2024-01-15 13:00:54 +03:00
### Default Validations
2023-08-11 17:47:49 +03:00
2024-01-15 13:00:54 +03:00
When you are using the default authentication flow, Wasp validates the fields with some default validations. These validations run if you use Wasp's built-in [Auth UI ](./ui ) or if you use the provided auth actions.
2023-11-15 15:05:00 +03:00
2024-01-15 13:00:54 +03:00
If you decide to create your [custom auth actions ](./username-and-pass#2-creating-your-custom-sign-up-action ), you'll need to run the validations yourself.
2023-08-11 17:47:49 +03:00
Default validations depend on the auth method you use.
2024-01-15 13:00:54 +03:00
#### Username & Password
2023-08-11 17:47:49 +03:00
2024-01-15 13:00:54 +03:00
If you use [Username & password ](./username-and-pass ) authentication, the default validations are:
2023-09-12 14:19:47 +03:00
2023-08-11 17:47:49 +03:00
- The `username` must not be empty
- The `password` must not be empty, have at least 8 characters, and contain a number
2024-01-15 13:00:54 +03:00
Note that `username` s are stored in a **case-insensitive** manner.
2023-08-11 17:47:49 +03:00
#### Email
2024-01-15 13:00:54 +03:00
If you use [Email ](./email ) authentication, the default validations are:
2023-09-12 14:19:47 +03:00
2023-08-11 17:47:49 +03:00
- The `email` must not be empty and a valid email address
- The `password` must not be empty, have at least 8 characters, and contain a number
Note that `email` s are stored in a **case-insensitive** manner.
2023-09-12 14:19:47 +03:00
## Customizing the Signup Process
2024-01-18 15:42:00 +03:00
Sometimes you want to include **extra fields** in your signup process, like first name and last name and save them in the `User` entity.
2023-09-12 14:19:47 +03:00
2024-01-18 15:42:00 +03:00
For this to happen:
2023-09-12 14:19:47 +03:00
- you need to define the fields that you want saved in the database,
2024-01-18 15:42:00 +03:00
- you need to customize the `SignupForm` (in the case of [Email ](./email ) or [Username & Password ](./username-and-pass ) auth)
2023-09-12 14:19:47 +03:00
Other times, you might need to just add some **extra UI** elements to the form, like a checkbox for terms of service. In this case, customizing only the UI components is enough.
Let's see how to do both.
### 1. Defining Extra Fields
If we want to **save** some extra fields in our signup process, we need to tell our app they exist.
We do that by defining an object where the keys represent the field name, and the values are functions that receive the data sent from the client\* and return the value of the field.
< small >
\* We exclude the `password` field from this object to prevent it from being saved as plain-text in the database. The `password` field is handled by Wasp's auth backend.
< / small >
2024-01-18 15:42:00 +03:00
First, we add the `auth.methods.{authMethod}.userSignupFields` field in our `main.wasp` file. The `{authMethod}` depends on the auth method you are using.
For example, if you are using [Username & Password ](./username-and-pass ), you would add the `auth.methods.usernameAndPassword.userSignupFields` field:
2023-09-12 14:19:47 +03:00
< Tabs groupId = "js-ts" >
< TabItem value = "js" label = "JavaScript" >
2024-01-18 15:42:00 +03:00
```wasp title="main.wasp"
2023-09-12 14:19:47 +03:00
app crudTesting {
// ...
auth: {
userEntity: User,
methods: {
2024-01-18 15:42:00 +03:00
usernameAndPassword: {
2024-02-23 15:03:43 +03:00
userSignupFields: import { userSignupFields } from "@src/auth/signup",
2024-01-18 15:42:00 +03:00
},
2023-09-12 14:19:47 +03:00
},
onAuthFailedRedirectTo: "/login",
},
}
entity User {=psl
id Int @id @default (autoincrement())
address String?
psl=}
```
2024-02-23 15:03:43 +03:00
Then we'll define the `userSignupFields` object in the `src/auth/signup.js` file:
2023-09-12 14:19:47 +03:00
2024-02-23 15:03:43 +03:00
```ts title="src/auth/signup.js"
import { defineUserSignupFields } from 'wasp/server/auth'
2023-09-12 14:19:47 +03:00
2024-01-18 15:42:00 +03:00
export const userSignupFields = defineUserSignupFields({
2023-09-12 14:19:47 +03:00
address: async (data) => {
const address = data.address
if (typeof address !== 'string') {
throw new Error('Address is required')
}
if (address.length < 5 ) {
throw new Error('Address must be at least 5 characters long')
}
return address
},
})
```
< / TabItem >
< TabItem value = "ts" label = "TypeScript" >
2024-01-18 15:42:00 +03:00
```wasp title="main.wasp"
2023-09-12 14:19:47 +03:00
app crudTesting {
// ...
auth: {
userEntity: User,
methods: {
2024-01-18 15:42:00 +03:00
usernameAndPassword: {
2024-02-23 15:07:28 +03:00
userSignupFields: import { userSignupFields } from "@src/auth/signup",
2024-01-18 15:42:00 +03:00
},
2023-09-12 14:19:47 +03:00
},
onAuthFailedRedirectTo: "/login",
},
}
entity User {=psl
id Int @id @default (autoincrement())
address String?
psl=}
```
2024-02-23 15:03:43 +03:00
Then we'll define the `userSignupFields` object in the `src/auth/signup.js` file:
2023-09-12 14:19:47 +03:00
2024-02-23 15:03:43 +03:00
```ts title="src/auth/signup.ts"
import { defineUserSignupFields } from 'wasp/server/auth'
2023-09-12 14:19:47 +03:00
2024-01-18 15:42:00 +03:00
export const userSignupFields = defineUserSignupFields({
2023-09-12 14:19:47 +03:00
address: async (data) => {
const address = data.address
if (typeof address !== 'string') {
throw new Error('Address is required')
}
if (address.length < 5 ) {
throw new Error('Address must be at least 5 characters long')
}
return address
},
})
```
< / TabItem >
< / Tabs >
< small >
2024-01-18 15:42:00 +03:00
Read more about the `userSignupFields` object in the [API Reference ](#signup-fields-customization ).
2023-09-12 14:19:47 +03:00
< / small >
Keep in mind, that these field names need to exist on the `userEntity` you defined in your `main.wasp` file e.g. `address` needs to be a field on the `User` entity.
The field function will receive the data sent from the client and it needs to return the value that will be saved into the database. If the field is invalid, the function should throw an error.
:::info Using Validation Libraries
You can use any validation library you want to validate the fields. For example, you can use `zod` like this:
< details >
< summary > Click to see the code< / summary >
< Tabs groupId = "js-ts" >
< TabItem value = "js" label = "JavaScript" >
2024-02-23 15:03:43 +03:00
```js title="src/auth/signup.js"
import { defineUserSignupFields } from 'wasp/server/auth'
2023-09-12 14:19:47 +03:00
import * as z from 'zod'
2024-01-18 15:42:00 +03:00
export const userSignupFields = defineUserSignupFields({
2023-09-12 14:19:47 +03:00
address: (data) => {
const AddressSchema = z
.string({
required_error: 'Address is required',
invalid_type_error: 'Address must be a string',
})
.min(10, 'Address must be at least 10 characters long')
const result = AddressSchema.safeParse(data.address)
if (result.success === false) {
throw new Error(result.error.issues[0].message)
}
return result.data
},
})
```
< / TabItem >
< TabItem value = "ts" label = "TypeScript" >
2024-02-23 15:03:43 +03:00
```ts title="src/auth/signup.ts"
import { defineUserSignupFields } from 'wasp/server/auth'
2023-09-12 14:19:47 +03:00
import * as z from 'zod'
2024-01-18 15:42:00 +03:00
export const userSignupFields = defineUserSignupFields({
2023-09-12 14:19:47 +03:00
address: (data) => {
const AddressSchema = z
.string({
required_error: 'Address is required',
invalid_type_error: 'Address must be a string',
})
.min(10, 'Address must be at least 10 characters long')
const result = AddressSchema.safeParse(data.address)
if (result.success === false) {
throw new Error(result.error.issues[0].message)
}
return result.data
},
})
```
< / TabItem >
< / Tabs >
< / details >
:::
Now that we defined the fields, Wasp knows how to:
1. Validate the data sent from the client
2. Save the data to the database
2024-01-12 19:42:53 +03:00
Next, let's see how to customize [Auth UI ](../auth/ui ) to include those fields.
2023-09-12 14:19:47 +03:00
### 2. Customizing the Signup Component
:::tip Using Custom Signup Component
If you are not using Wasp's Auth UI, you can skip this section. Just make sure to include the extra fields in your custom signup form.
Read more about using the signup actions for:
2024-01-12 19:42:53 +03:00
- email auth [here ](../auth/email#fields-in-the-email-dict ) <!-- TODO: these docs are not great at explaining using signup and login actions: https://github.com/wasp-lang/wasp/issues/1438 -->
- username & password auth [here ](../auth/username-and-pass#customizing-the-auth-flow )
2023-09-12 14:19:47 +03:00
:::
If you are using Wasp's Auth UI, you can customize the `SignupForm` component by passing the `additionalFields` prop to it. It can be either a list of extra fields or a render function.
#### Using a List of Extra Fields
When you pass in a list of extra fields to the `SignupForm` , they are added to the form one by one, in the order you pass them in.
Inside the list, there can be either **objects** or **render functions** (you can combine them):
1. Objects are a simple way to describe new fields you need, but a bit less flexible than render functions.
2. Render functions can be used to render any UI you want, but they require a bit more code. The render functions receive the `react-hook-form` object and the form state object as arguments.
< Tabs groupId = "js-ts" >
< TabItem value = "js" label = "JavaScript" >
2024-02-23 15:03:43 +03:00
```jsx title="src/SignupPage.jsx"
2023-09-12 14:19:47 +03:00
import {
2024-02-23 15:03:43 +03:00
SignupForm,
2023-09-12 14:19:47 +03:00
FormError,
FormInput,
FormItemGroup,
FormLabel,
2024-02-23 15:03:43 +03:00
} from 'wasp/client/auth'
2023-09-12 14:19:47 +03:00
export const SignupPage = () => {
return (
< SignupForm
additionalFields={[
/* The address field is defined using an object */
{
name: 'address',
label: 'Address',
type: 'input',
validations: {
required: 'Address is required',
},
},
/* The phone number is defined using a render function */
(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 >
)
},
]}
/>
)
}
```
< / TabItem >
< TabItem value = "ts" label = "TypeScript" >
2024-02-23 15:03:43 +03:00
```tsx title="src/SignupPage.tsx"
2023-09-12 14:19:47 +03:00
import {
2024-02-23 15:03:43 +03:00
SignupForm,
2023-09-12 14:19:47 +03:00
FormError,
FormInput,
FormItemGroup,
FormLabel,
2024-02-23 15:03:43 +03:00
} from 'wasp/client/auth'
2023-09-12 14:19:47 +03:00
export const SignupPage = () => {
return (
< SignupForm
additionalFields={[
/* The address field is defined using an object */
{
name: 'address',
label: 'Address',
type: 'input',
validations: {
required: 'Address is required',
},
},
/* The phone number is defined using a render function */
(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 >
)
},
]}
/>
)
}
```
< / TabItem >
< / Tabs >
< small >
Read more about the extra fields in the [API Reference ](#signupform-customization ).
< / small >
#### Using a Single Render Function
Instead of passing in a list of extra fields, you can pass in a render function which will receive the `react-hook-form` object and the form state object as arguments. What ever the render function returns, will be rendered below the default fields.
< Tabs groupId = "js-ts" >
< TabItem value = "js" label = "JavaScript" >
2024-02-23 15:03:43 +03:00
```jsx title="src/SignupPage.jsx"
import { SignupForm, FormItemGroup } from 'wasp/client/auth'
2023-09-12 14:19:47 +03:00
export const SignupPage = () => {
return (
< SignupForm
additionalFields={(form, state) => {
const username = form.watch('username')
return (
username & & (
< FormItemGroup >
Hello there < strong > {username}< / strong > 👋
< / FormItemGroup >
)
)
}}
/>
)
}
```
< / TabItem >
< TabItem value = "ts" label = "TypeScript" >
2024-02-23 15:03:43 +03:00
```tsx title="src/SignupPage.tsx"
import { SignupForm, FormItemGroup } from 'wasp/client/auth'
2023-09-12 14:19:47 +03:00
export const SignupPage = () => {
return (
< SignupForm
additionalFields={(form, state) => {
const username = form.watch('username')
return (
username & & (
< FormItemGroup >
Hello there < strong > {username}< / strong > 👋
< / FormItemGroup >
)
)
}}
/>
)
}
```
< / TabItem >
< / Tabs >
< small >
Read more about the render function in the [API Reference ](#signupform-customization ).
< / small >
2023-08-11 17:47:49 +03:00
## API Reference
2023-09-12 14:19:47 +03:00
### Auth Fields
2023-08-11 17:47:49 +03:00
< Tabs groupId = "js-ts" >
< TabItem value = "js" label = "JavaScript" >
```wasp title="main.wasp"
title: "My app",
//...
auth: {
userEntity: User,
methods: {
usernameAndPassword: {}, // use this or email, not both
email: {}, // use this or usernameAndPassword, not both
google: {},
gitHub: {},
},
2023-09-12 14:19:47 +03:00
onAuthFailedRedirectTo: "/someRoute",
signup: { ... }
2023-08-11 17:47:49 +03:00
}
}
//...
```
2023-09-12 14:19:47 +03:00
2023-08-11 17:47:49 +03:00
< / TabItem >
< TabItem value = "ts" label = "TypeScript" >
```wasp title="main.wasp"
app MyApp {
title: "My app",
//...
auth: {
userEntity: User,
methods: {
usernameAndPassword: {}, // use this or email, not both
email: {}, // use this or usernameAndPassword, not both
google: {},
gitHub: {},
},
2023-09-12 14:19:47 +03:00
onAuthFailedRedirectTo: "/someRoute",
signup: { ... }
2023-08-11 17:47:49 +03:00
}
}
//...
```
2023-09-12 14:19:47 +03:00
2023-08-11 17:47:49 +03:00
< / TabItem >
< / Tabs >
`app.auth` is a dictionary with the following fields:
#### `userEntity: entity` <Required />
2023-09-12 14:19:47 +03:00
2024-01-15 13:00:54 +03:00
The entity representing the user connected to your business logic.
2023-08-11 17:47:49 +03:00
2024-01-15 13:00:54 +03:00
< ReadMoreAboutAuthEntities / >
2023-08-11 17:47:49 +03:00
#### `methods: dict` <Required />
2023-09-12 14:19:47 +03:00
2023-08-11 17:47:49 +03:00
A dictionary of auth methods enabled for the app.
< AuthMethodsGrid / >
#### `onAuthFailedRedirectTo: String` <Required />
2023-09-12 14:19:47 +03:00
2023-08-11 17:47:49 +03:00
The route to which Wasp should redirect unauthenticated user when they try to access a private page (i.e., a page that has `authRequired: true` ).
2024-01-12 19:42:53 +03:00
Check out these [essentials docs on auth ](../tutorial/auth#adding-auth-to-the-project ) to see an example of usage.
2023-08-11 17:47:49 +03:00
#### `onAuthSucceededRedirectTo: String`
2023-09-12 14:19:47 +03:00
2023-08-11 17:47:49 +03:00
The route to which Wasp will send a successfully authenticated after a successful login/signup.
The default value is `"/"` .
:::note
2024-01-12 19:42:53 +03:00
Automatic redirect on successful login only works when using the Wasp-provided [Auth UI ](../auth/ui ).
2023-08-11 17:47:49 +03:00
:::
2023-09-12 14:19:47 +03:00
#### `signup: SignupOptions`
Read more about the signup process customization API in the [Signup Fields Customization ](#signup-fields-customization ) section.
### Signup Fields Customization
2024-01-18 15:42:00 +03:00
If you want to add extra fields to the signup process, the server needs to know how to save them to the database. You do that by defining the `auth.methods.{authMethod}.userSignupFields` field in your `main.wasp` file.
2023-09-12 14:19:47 +03:00
< Tabs groupId = "js-ts" >
< TabItem value = "js" label = "JavaScript" >
2024-01-18 15:42:00 +03:00
```wasp title="main.wasp"
2023-09-12 14:19:47 +03:00
app crudTesting {
// ...
auth: {
userEntity: User,
methods: {
2024-01-18 15:42:00 +03:00
usernameAndPassword: {
// highlight-next-line
2024-02-23 15:07:28 +03:00
userSignupFields: import { userSignupFields } from "@src/auth/signup",
2024-01-18 15:42:00 +03:00
},
2023-09-12 14:19:47 +03:00
},
onAuthFailedRedirectTo: "/login",
},
}
```
2024-02-23 15:03:43 +03:00
Then we'll export the `userSignupFields` object from the `src/auth/signup.js` file:
2023-09-12 14:19:47 +03:00
2024-02-23 15:03:43 +03:00
```ts title="src/auth/signup.js"
import { defineUserSignupFields } from 'wasp/server/auth'
2023-09-12 14:19:47 +03:00
2024-01-18 15:42:00 +03:00
export const userSignupFields = defineUserSignupFields({
2023-09-12 14:19:47 +03:00
address: async (data) => {
const address = data.address
if (typeof address !== 'string') {
throw new Error('Address is required')
}
if (address.length < 5 ) {
throw new Error('Address must be at least 5 characters long')
}
return address
},
})
```
< / TabItem >
< TabItem value = "ts" label = "TypeScript" >
2024-01-18 15:42:00 +03:00
```wasp title="main.wasp"
2023-09-12 14:19:47 +03:00
app crudTesting {
// ...
auth: {
userEntity: User,
methods: {
2024-01-18 15:42:00 +03:00
usernameAndPassword: {
// highlight-next-line
2024-02-23 15:07:28 +03:00
userSignupFields: import { userSignupFields } from "@src/auth/signup",
2024-01-18 15:42:00 +03:00
},
2023-09-12 14:19:47 +03:00
},
onAuthFailedRedirectTo: "/login",
},
}
```
2024-02-23 15:03:43 +03:00
Then we'll export the `userSignupFields` object from the `src/auth/signup.ts` file:
2023-09-12 14:19:47 +03:00
2024-02-23 15:03:43 +03:00
```ts title="src/auth/signup.ts"
import { defineUserSignupFields } from 'wasp/server/auth'
2023-09-12 14:19:47 +03:00
2024-01-18 15:42:00 +03:00
export const userSignupFields = defineUserSignupFields({
2023-09-12 14:19:47 +03:00
address: async (data) => {
const address = data.address
if (typeof address !== 'string') {
throw new Error('Address is required')
}
if (address.length < 5 ) {
throw new Error('Address must be at least 5 characters long')
}
return address
},
})
```
< / TabItem >
< / Tabs >
2024-01-18 15:42:00 +03:00
The `userSignupFields` object is an object where the keys represent the field name, and the values are functions that receive the data sent from the client\* and return the value of the field.
2023-09-12 14:19:47 +03:00
2024-01-18 15:42:00 +03:00
If the value that the function received is invalid, the function should throw an error.
2023-09-12 14:19:47 +03:00
< small >
2024-01-18 15:42:00 +03:00
\* We exclude the `password` field from this object to prevent it from being saved as plain text in the database. The `password` field is handled by Wasp's auth backend.
2023-09-12 14:19:47 +03:00
< / small >
### `SignupForm` Customization
To customize the `SignupForm` component, you need to pass in the `additionalFields` prop. It can be either a list of extra fields or a render function.
< Tabs groupId = "js-ts" >
< TabItem value = "js" label = "JavaScript" >
2024-02-23 15:03:43 +03:00
```jsx title="src/SignupPage.jsx"
2023-09-12 14:19:47 +03:00
import {
2024-02-23 15:03:43 +03:00
SignupForm,
2023-09-12 14:19:47 +03:00
FormError,
FormInput,
FormItemGroup,
FormLabel,
2024-02-23 15:03:43 +03:00
} from 'wasp/client/auth'
2023-09-12 14:19:47 +03:00
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 >
)
},
]}
/>
)
}
```
< / TabItem >
< TabItem value = "ts" label = "TypeScript" >
2024-02-23 15:03:43 +03:00
```tsx title="src/SignupPage.tsx"
2023-09-12 14:19:47 +03:00
import {
2024-02-23 15:03:43 +03:00
SignupForm,
2023-09-12 14:19:47 +03:00
FormError,
FormInput,
FormItemGroup,
FormLabel,
2024-02-23 15:03:43 +03:00
} from 'wasp/client/auth'
2023-09-12 14:19:47 +03:00
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 >
)
},
]}
/>
)
}
```
< / TabItem >
< / Tabs >
The extra fields can be either **objects** or **render functions** (you can combine them):
1. Objects are a simple way to describe new fields you need, but a bit less flexible than render functions.
The objects 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. The keys are the validation names, and the values are the validation error messages. Read more about the available validation rules in the [react-hook-form docs ](https://react-hook-form.com/api/useform/register#register ).
2. Render functions receive the `react-hook-form` object and the form state as arguments, and they can use them to render arbitrary UI elements.
The render function has the following signature:
```ts
;(form: UseFormReturn, state: FormState) => React.ReactNode
```
- `form` < Required />
- the `react-hook-form` object, read more about it in the [react-hook-form docs ](https://react-hook-form.com/api/useform )
- you need to use the `form.register` function to register your fields
- `state` < Required />
- the form state object which has the following properties:
- `isLoading: boolean`
- whether the form is currently submitting