Skip to main content

Sign-in link

Put a one-tap sign-in link next to the email code, without a magic-link plugin.

Add a link to the email code email. The person taps the link, then taps one button, and is signed in. The link carries the same code, so it is as strong as the code: it has the same expiry (five minutes by default) and the same attempt limit (three wrong codes by default). The typed code still works.

This recipe needs emailOTP and an email hook. Better Convex does not support Better Auth's magic-link plugin.

Put the code and the address after # in the URL. The browser does not send this part (the fragment) to any server. So the code does not appear in the URL that server logs, proxies and the Referer header of the next page record. The confirming tap sends the code in a request body, as the typed code does. Do not log the bodies of auth requests.

convex/auth.ts
import {
  createBetterConvexAuth,
  requireAuthOrigin,
} from '@lupinum/better-convex-nuxt/better-auth/server'

import { components, internal } from './_generated/api'
import type { DataModel } from './_generated/dataModel'

export const auth = createBetterConvexAuth<DataModel>(components.betterAuth, {
  emailOTP: {},
  email: async (ctx, message) => {
    if (message.type === 'email-otp' && message.purpose === 'sign-in') {
      const fragment = new URLSearchParams({ code: message.otp, email: message.to })
      await ctx.runMutation(internal.authMail.submitSignInCode, {
        recipient: message.to,
        code: message.otp,
        url: `${requireAuthOrigin('SITE_URL')}/sign-in#${fragment}`,
      })
      return
    }
    // Keep the cases for the other messages that your hook already sends.
    throw new Error(`Unsupported auth email: ${message.type}`)
  },
})

internal.authMail.submitSignInCode is your own internal mutation. It queues the email with the code and the link. See Transactional auth email. Show the code in the email too, for a person who reads mail on another device.

Ask for one tap

Mail scanners and link previews open links before the person does. Do not sign in when the page loads. Read the fragment, remove it from the address bar, and wait for the person to tap the button.

Show the email address before the tap. An attacker can send a victim a link with the attacker's own code. Without the address on the page, the victim would sign in to the attacker's account and put private data there.

app/pages/sign-in.vue
<script setup lang="ts">
definePageMeta({ convexAuth: 'guest' })

const { client } = useConvexAuth()
const link = ref<{ code: string; email: string } | null>(null)
const busy = ref(false)
const formError = ref('')

function readLink() {
  const params = new URLSearchParams(window.location.hash.slice(1))
  const code = params.get('code') ?? ''
  const email = params.get('email') ?? ''
  if (window.location.hash) {
    // Remove the code from the address bar and from the browser history entry.
    history.replaceState(history.state, '', window.location.pathname + window.location.search)
  }
  // Six digits is the default `emailOTP.otpLength`.
  if (/^\d{6}$/.test(code) && email.includes('@')) link.value = { code, email }
}

onMounted(() => {
  readLink()
  // The link can open in a tab that already shows this page.
  window.addEventListener('hashchange', readLink)
})
onBeforeUnmount(() => window.removeEventListener('hashchange', readLink))

async function confirmLink() {
  if (!link.value) return
  busy.value = true
  const { code, email } = link.value
  const result = await client.signIn.emailOtp({ email, otp: code })
  busy.value = false
  if (result.error) {
    formError.value = 'The link has expired. Ask for a new code.'
    link.value = null
    return
  }
  await navigateTo('/')
}
</script>

<template>
  <section v-if="link">
    <p>Sign in as {{ link.email }}?</p>
    <button type="button" :disabled="busy" @click="confirmLink">Sign in</button>
    <button type="button" @click="link = null">Type the code instead</button>
  </section>
  <section v-else>
    <p v-if="formError" role="alert">{{ formError }}</p>
    <!-- Your email and code form from the email code sign-in example. -->
  </section>
</template>