DEV Community

Cover image for How to add Anonymous Authentication to your Next.js App using Supabase
Anjan Shomodder
Anjan Shomodder

Posted on

How to add Anonymous Authentication to your Next.js App using Supabase

Why Anonymous Authentication?

Let's say you have an e-commerce app, and you want to allow users to add products
to cart and complete checkout. The process should be as simple as possible for the user. However, if you ask them to sign up or log in before they can add products to their cart, they might lose interest and leave the app. This is where anonymous authentication comes in handy. An anonymous account is a temporary account you create on behalf of the user. Now, users won't have to create an account to purchase products. And, of course, you can convert them to permanent accounts, which I will explain at the end.

Video Tutorial

Enabling Anonymous Authentication in Supabase

  • Create a new Project in Supabase.com

    • You might need to create a new organization if you don't have one.
    • Then give your project name and db password
    • Once the project is created, you will have the project URL and anon key. You can use these to connect to your project.
    • Note that these are public keys, and you can share them. Like Firebase, you protect your data with rules.
  • Go to the Authentication section in Supabase

  • Then go to the sign section

  • Enable Anonymous Authentication

Get the complete source code from here

Adding Anonymous Authentication to Next.js

  • Create a server action in Next.js
'use server'
const signinAnonymously = async () => {
  const supabase = await createClientForServer()

  const { error } = await supabase.auth.signInAnonymously()

  if (error) {
    console.error('Error signing in anonymously:', error)
    return
  }

  console.log('Signed in anonymously successfully')

  revalidatePath('/')
}
Enter fullscreen mode Exit fullscreen mode
  • Create a button in your Next.js component to trigger the server action
    • Add formAction attribute to the button to call the server action
<form className='flex gap-4 mb-4'>
  <button
    className='bg-green-600 text-white rounded px-4 py-2 hover:bg-green-700 transition'
    formAction={signinAnonymously}
  >
    Login Anonymously
  </button>
</form>
Enter fullscreen mode Exit fullscreen mode
  • Now, Just click the button to sign in anonymously, and you should see a new user on the dashboard in Supabase

Get the current user in Next.js

const supabase = await createClientForServer()

const {
  data: { user },
  error,
} = await supabase.auth.getUser()

if (error) {
  console.error('Error fetching user:', error)
} else {
  console.log('User data:', user)
}
Enter fullscreen mode Exit fullscreen mode
- Just use the `supabase.auth.getUser()` method to get the current user in your Next.js app.
Enter fullscreen mode Exit fullscreen mode

Check if the user is anonymous

The user object will have an is_anonymous property that you can check to see if the user is anonymous.

Convert Anonymous User to Permanent User

  • To convert an anonymous user to a permanent user, you can use the updateUser method in Supabase.
'use server'
const updateUser = async formData => {
  const supabase = await createClientForServer()

  const { error } = await supabase.auth.updateUser({
    email: formData.get('email'),
    password: formData.get('password'),
  })

  if (error) {
    console.error('Error updating user:', error)
    return
  }

  console.log('User updated successfully, Please confiirm your email')
}
Enter fullscreen mode Exit fullscreen mode
  • Create a form to update the user
<form
  action={updateUser}
  className='flex flex-col gap-4 border rounded-lg p-6 shadow w-full sm:w-96 bg-gray-50 dark:bg-neutral-900'
>
  <h2 className='text-lg font-semibold mb-2'>Update User</h2>
  <label className='flex flex-col gap-1'>
    <span className='text-sm font-medium'>Email</span>
    <input
      type='email'
      name='email'
      className='border rounded px-3 py-2 bg-white dark:bg-neutral-800'
      required
      autoComplete='off'
    />
  </label>
  <label className='flex flex-col gap-1'>
    <span className='text-sm font-medium'>Password</span>
    <input
      type='password'
      name='password'
      className='border rounded px-3 py-2 bg-white dark:bg-neutral-800'
      required
      autoComplete='off'
    />
  </label>
  <button
    type='submit'
    className='mt-2 bg-blue-600 text-white rounded px-4 py-2 hover:bg-blue-700 transition'
  >
    Update
  </button>
</form>
Enter fullscreen mode Exit fullscreen mode
  • Now, when you submit the form, it will send a confirmation email to the user to verify their email address.
  • If the email is not verified, the account will remain anonymous.

Login after email verification

  • Once you verify the email, the user will be able to log in using the email and password.
<form
          className='flex flex-col gap-4 border rounded-lg p-6 shadow w-full sm:w-96 bg-gray-50 dark:bg-neutral-900'
          action={loginWithPassword}
        >
          <h2 className='text-lg font-semibold mb-2'>Login</h2>
          <label className='flex flex-col gap-1'>
            <span className='text-sm font-medium'>Email</span>
            <input
              type='email'
              name='email'
              className='border rounded px-3 py-2 bg-white dark:bg-neutral-800'
              required
              autoComplete='off'
            />
          </label>
          <label className='flex flex-col gap-1'>
            <span className='text-sm font-medium'>Password</span>
            <input
              type='password'
              name='password'
              className='border rounded px-3 py-2 bg-white dark:bg-neutral-800'
              required
              autoComplete='off'
            />
          </label>
          <button
            type='submit'
            className='mt-2 bg-green-600 text-white rounded px-4 py-2 hover:bg-green-700 transition'
          >
            Login
          </button>
        </form>
Enter fullscreen mode Exit fullscreen mode
const loginWithPassword = async formData => {
  const supabase = await createClientForServer()

  const { error } = await supabase.auth.signInWithPassword({
    email: formData.get('email'),
    password: formData.get('password'),
  })

  if (error) {
    console.error('Error logging in with password:', error)
    return
  }

  console.log('User logged in successfully')

  revalidatePath('/')
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

Tha's it! You have successfully implemented anonymous authentication in your Next.js app using Supabase. Subscribe to my YouTube channel for more tutorials like this. If you have any questions, feel free to ask in the comments section below. Happy coding! 😊

Videos you might like





Top comments (2)

Collapse
 
dotallio profile image
Dotallio

Super clear guide, thanks! Have you run into any tricky cases with merging carts once a user upgrades from anonymous to permanent?

Collapse
 
thatanjan profile image
Anjan Shomodder

Well, converting an anonymous user to a permanent user doesn't change the user object or the ID. So, if you store cart information and have a reference to the user ID, then you should be good to go.

But if you want to link an anonymous user to an existing permanent account, then you have to handle data conflicts manually. Supabase docs have a good example for that.

https://supabase.com/docs/guides/auth/auth-anonymous?queryGroups=language&language=js#resolving-identity-conflicts

Hope it helps!