Files
Miranda Limonczenko 58b468916c docs(auth): Solve eval for Anonymous sign-in page (#53489)
Closes DOCS-1676

## Problem

The drafted Eval for this guide has one failing check. This PR fixes
that check and also runs the `edit-the-docs` and `test-the-docs` skill
to improve the page as a whole.

The Anonymous Sign-Ins guide tells readers to check the `is_anonymous`
JWT claim in RLS policies. When a guest links an email, phone, or OAuth
identity, the user becomes permanent at once, but the token the client
holds keeps `is_anonymous: true` until it refreshes. A policy on the
claim refuses that new customer with `42501` until then.

## What changed

- **Access control:** a caution on the stale claim, and a policy that
reads `auth.users.is_anonymous` through a `security definer` function in
a non-exposed schema with `search_path = ''`.
- **Convert an anonymous user:** a "Refresh the session after linking"
step with `refreshSession()`.
- **Whole-page edit**, one commit per change type:
- Style: wording, word list, sentence-case and imperative headings, no
time-anchored text.
- Structure (moves only): Access control before Convert, identity
conflicts under Convert, the Next.js caution under Sign in.
- Technical: the `anon` key uses the `anon` role, not `anonymous`; the
opening caution no longer says to check the JWT claim; the
existing-account sample throws instead of a top-level `return`.

Renamed headings with no inbound links: Resolving identity conflicts,
Linking an anonymous user to an existing account, Automatic cleanup.
`#access-control` (Studio) and `#link-an-email--phone-identity` are
unchanged.

## Eval on the preview

`build-docs-016-auth-anonymous` with `REFERENCE` pointed at the preview,
3 runs ([workflow
run](https://github.com/supabase/evals/actions/runs/43983385855)).

| Run | Score | Guest who just made an account can post a review |
Failed check |
| --- | --- | --- | --- |
| Baseline (published page) | 9/10 in all 3 runs | Fail in all 3 | Guest
who just made an account can post a review |
| 1 | 10/10 | Pass | None |
| 2 | 9/10 | Pass | Agent read the guide |
| 3 | 9/10 | Pass | Agent read the guide |

All 3 runs fetched the preview and wrote the `security definer` policy.
The guide-read check only counts fetches from `supabase.com`, so it
can't pass on a preview. Run 1 passed it because that agent also opened
the published page.

## Manual testing

1. Open the [Anonymous sign-ins
preview](https://docs-git-docs-anonymous-claim-refresh-supabase.vercel.app/docs/guides/auth/auth-anonymous).
2. Check the new caution and function example under **Access control**,
and the new **Refresh the session after linking** section.
3. Click the anchor links between the two sections and to the RLS guide.
2026-12-01 10:13:18 -08:00

292 lines
9.3 KiB
Plaintext

---
id: 'auth-anonymous-convert'
title: 'Convert an anonymous user'
description: 'Convert an anonymous user to a permanent user by linking an email, phone, or OAuth identity, and refresh the session so row-level security sees the change.'
---
Link an identity to an anonymous user to make them a permanent user and keep their data.
## Prerequisites
To convert an anonymous user, you need:
- A user signed in with [anonymous sign-ins](/docs/guides/auth/auth-anonymous).
- [Manual linking enabled](/dashboard/project/_/auth/providers) in your Supabase project. Converting a user requires [linking an identity](/docs/guides/auth/auth-identity-linking#manual-linking-beta).
## Link an email / phone identity
<Tabs
scrollable
size="small"
type="underlined"
defaultActiveId="js"
queryGroup="language"
>
<TabPanel id="js" label="JavaScript">
Use [`updateUser()`](/docs/reference/javascript/auth-updateuser) to link an email or phone identity to the anonymous user. The user must verify their email address or phone number before you can add a password.
```js
import { createClient } from '@supabase/supabase-js'
const supabase = createClient('https://your-project-id.supabase.co', 'sb_publishable_...')
// ---cut---
const { data: updateEmailData, error: updateEmailError } = await supabase.auth.updateUser({
email: 'valid.email@supabase.io',
})
// verify the user's email by clicking on the email change link
// or entering the 6-digit OTP sent to the email address
// once the user has been verified, update the password
const { data: updatePasswordData, error: updatePasswordError } = await supabase.auth.updateUser({
password: 'password',
})
```
</TabPanel>
<$Show if="sdk:dart">
<TabPanel id="dart" label="Flutter">
Use [`updateUser()`](/docs/reference/dart/auth-updateuser) to link an email or phone identity to the anonymous user.
```dart
await supabase.auth.updateUser(UserAttributes(email: 'valid.email@supabase.io'));
```
</TabPanel>
</$Show>
<$Show if="sdk:swift">
<TabPanel id="swift" label="Swift">
Use [`update(user:)`](/docs/reference/swift/auth-updateuser) to link an email or phone identity to the anonymous user.
```swift
try await supabase.auth.update(
user: UserAttributes(email: "valid.email@supabase.io")
)
```
</TabPanel>
</$Show>
<$Show if="sdk:kotlin">
<TabPanel id="kotlin" label="Kotlin">
Use [`updateUser()`](/docs/reference/kotlin/auth-updateuser) to link an email or phone identity to the anonymous user.
```kotlin
supabase.auth.updateUser {
email = "valid.email@supabase.io"
}
```
</TabPanel>
</$Show>
<$Show if="sdk:python">
<TabPanel id="python" label="Python">
Use [`update_user()`](/docs/reference/python/auth-updateuser) to link an email or phone identity to the anonymous user. The user must verify their email address or phone number before you can add a password.
```python
response = supabase.auth.update_user({
'email': 'valid.email@supabase.io',
})
# verify the user's email by clicking on the email change link
# or entering the 6-digit OTP sent to the email address
# once the user has been verified, update the password
response = supabase.auth.update_user({
'password': 'password',
})
```
</TabPanel>
</$Show>
<$Show if="sdk:csharp">
<TabPanel id="csharp" label="C#">
Use [`Update()`](/docs/reference/csharp/auth-updateuser) to link an email or phone identity to the anonymous user. The user must verify their email address or phone number before you can add a password.
```c#
var updateEmail = await supabase.Auth.Update(new UserAttributes { Email = "valid.email@supabase.io" });
// verify the user's email by clicking on the email change link
// or entering the 6-digit OTP sent to the email address
// once the user has been verified, update the password
var updatePassword = await supabase.Auth.Update(new UserAttributes { Password = "password" });
```
</TabPanel>
</$Show>
</Tabs>
## Link an OAuth identity
<Tabs
scrollable
size="small"
type="underlined"
defaultActiveId="js"
queryGroup="language"
>
<TabPanel id="js" label="JavaScript">
Use [`linkIdentity()`](/docs/reference/javascript/auth-linkidentity) to link an OAuth identity to the anonymous user.
```js
import { createClient } from '@supabase/supabase-js'
const supabase = createClient('https://your-project-id.supabase.co', 'sb_publishable_...')
// ---cut---
const { data, error } = await supabase.auth.linkIdentity({ provider: 'google' })
```
</TabPanel>
<$Show if="sdk:dart">
<TabPanel id="dart" label="Flutter">
Use [`linkIdentity()`](/docs/reference/dart/auth-linkidentity) to link an OAuth identity to the anonymous user.
```dart
await supabase.auth.linkIdentity(OAuthProvider.google);
```
</TabPanel>
</$Show>
<$Show if="sdk:swift">
<TabPanel id="swift" label="Swift">
Use [`linkIdentity()`](/docs/reference/swift/auth-linkidentity) to link an OAuth identity to the anonymous user.
```swift
try await supabase.auth.linkIdentity(provider: .google)
```
</TabPanel>
</$Show>
<$Show if="sdk:kotlin">
<TabPanel id="kotlin" label="Kotlin">
Use [`linkIdentity()`](/docs/reference/kotlin/auth-linkidentity) to link an OAuth identity to the anonymous user.
```kotlin
supabase.auth.linkIdentity(Google)
```
</TabPanel>
</$Show>
<$Show if="sdk:python">
<TabPanel id="python" label="Python">
Use [`link_identity()`](/docs/reference/python/auth-linkidentity) to link an OAuth identity to the anonymous user.
```python
response = supabase.auth.link_identity({'provider': 'google'})
```
</TabPanel>
</$Show>
<$Show if="sdk:csharp">
<TabPanel id="csharp" label="C#">
Use [`LinkIdentity()`](/docs/reference/csharp/auth-linkidentity) to link an OAuth identity to the anonymous user.
```c#
var state = await supabase.Auth.LinkIdentity(Provider.Google, new SignInOptions { FlowType = OAuthFlowType.PKCE });
var authorizeUrl = state.Uri;
```
</TabPanel>
</$Show>
</Tabs>
## Refresh the session after linking
Linking an identity makes the user permanent at once, but the access token the client holds still has `is_anonymous: true` until the session refreshes. RLS policies that check the claim keep treating the user as anonymous until then. Refresh the session after linking so the next request carries the updated claim:
```js
import { createClient } from '@supabase/supabase-js'
const supabase = createClient('https://your-project-id.supabase.co', 'sb_publishable_...')
// ---cut---
const { data, error } = await supabase.auth.refreshSession()
```
To write policies that don't depend on the token, see [Restrict anonymous user access](/docs/guides/auth/auth-anonymous/access-control).
## Resolve identity conflicts
Data conflicts can arise when an anonymous user becomes a permanent user. For example, an e-commerce app might let an anonymous user add items to a cart without signing up or signing in. When that user signs in to an existing account, decide how to resolve conflicts in the cart:
1. Overwrite the items in the cart with those in the existing account
2. Overwrite the items in the cart with those from the anonymous user
3. Merge the items in the cart together
### Link an anonymous user to an existing account
To link an anonymous user to an existing account instead of creating a new permanent account, handle the conflicts yourself. A general approach:
```js
import { createClient } from '@supabase/supabase-js'
const supabase = createClient('https://your-project-id.supabase.co', 'sb_publishable_...')
// ---cut---
// 1. Get the current session and verify the user is anonymous
const { data: anonData, error: anonError } = await supabase.auth.getSession()
if (!anonData.session?.user?.is_anonymous) {
throw new Error('User is not anonymous. This flow only applies to anonymous users.')
}
// 2. Attempt to update the user with the existing email
const { data: updateData, error: updateError } = await supabase.auth.updateUser({
email: 'valid.email@supabase.io',
})
// 3. Handle the error (since the email belongs to an existing user)
if (updateError) {
console.log('This email belongs to an existing user. Please sign in to that account.')
// 4. Sign in to the existing account
const {
data: { user: existingUser },
error: signInError,
} = await supabase.auth.signInWithPassword({
email: 'valid.email@supabase.io',
password: 'user_password',
})
if (existingUser) {
// 5. Reassign entities tied to the anonymous user
// This step will vary based on your specific use case and data model
const { data: reassignData, error: reassignError } = await supabase
.from('your_table')
.update({ user_id: existingUser.id })
.eq('user_id', anonData.session.user.id)
// 6. Implement your chosen conflict resolution strategy
// This could involve merging data, overwriting, or other custom logic
await resolveDataConflicts(anonData.session.user.id, existingUser.id)
}
}
// Helper function to resolve data conflicts (implement based on your strategy)
async function resolveDataConflicts(anonymousUserId, existingUserId) {
// Implement your conflict resolution logic here
// This could involve ignoring the anonymous user's metadata, overwriting the existing user's metadata, or merging the data of both the anonymous and existing user.
}
```
## Next steps
To keep going, use these pages:
- [Restrict anonymous user access](/docs/guides/auth/auth-anonymous/access-control): write policies that treat a linked user as permanent.
- [Identity linking](/docs/guides/auth/auth-identity-linking): manage the identities on a permanent user.