Supabase phone auth in India: OTP login with DiOTP and an Edge Function
Written by Vivek SinghReviewed by the DiOTP team Published 3 December 2026Last updated 3 December 2026
12 min read
Supabase phone auth in India works with DiOTP through an Edge Function, not through Supabase's Send SMS hook: the function sends and verifies the OTP with DiOTP, then issues a one-time token that the browser exchanges for a normal Supabase session. The hook cannot be used because Supabase generates its own code and asks you to deliver that text, while DiOTP generates the code itself and does not accept one from the caller. This guide explains that limit, builds the Edge Function with full error and rate-limit handling, and lists the trade-offs plainly.
Why the Send SMS hook does not fit DiOTP
Supabase Auth has a Send SMS hook: instead of using a built-in SMS provider, Supabase calls your HTTP endpoint or Postgres function with the user and the code it generated, and expects you to deliver that code. According to Supabase's documentation, the payload has a user object and an sms object whose otp field is the six-digit code, the request is signed with the Standard Webhooks scheme using a secret that starts with v1,whsec_, and a 200 reply with an empty body counts as success. Supabase then checks the code itself when the user types it.
DiOTP works the other way round. Its send endpoint accepts only the number, country_code, channel, purpose and an optional template id, and rejects any other field. It generates the code, sends it and checks it later through its verify endpoint. There is no way to hand DiOTP a code that Supabase made, so a Send SMS hook that delivers Supabase's OTP through DiOTP cannot be built. Any guide that shows one is describing something that will not work.
If you must keep Supabase's built-in phone provider and its Send SMS hook, you need an SMS route that sends arbitrary text you supply, which in India means your own DLT-registered header and template. DiOTP is an OTP API, so the design below uses DiOTP for the code and Supabase for the session.
The design that works
- The browser calls an Edge Function with action send and the phone number.
- The function calls DiOTP's send endpoint, stores the request_id with the phone in a private table and returns the request_id.
- The user types the code. The browser calls the function with action verify, the request_id and the code.
- The function calls DiOTP's verify endpoint, marks the request as used, finds or creates the Supabase user and generates a one-time sign-in token with the Admin API.
- The browser exchanges that token for a session with supabase.auth.verifyOtp. From here on it is a normal Supabase session: auth.uid(), row level security and refresh tokens all work as usual.
The DiOTP API key and the Supabase service role key stay inside the Edge Function. The browser never sees either. On DiOTP you can start without your own DLT registration, because codes go out on DiOTP's registered header and pre-approved template; see OTP without DLT.
Build it step by step
- Sign up for DiOTP and create an API key in the dashboard.
- In your Supabase project, add the otp_requests table below as a migration.
- Create the Edge Function with supabase functions new phone-otp and paste the code.
- Set the secrets: DIOTP_API_KEY, PHONE_EMAIL_DOMAIN and APP_ORIGIN.
- Deploy the function with --no-verify-jwt, because visitors are not signed in when they ask for a code.
- Call the function from your front end and exchange the token for a session.
otp_requests.sql
-- supabase/migrations/<timestamp>_otp_requests.sql
create table public.otp_requests (
request_id text primary key, -- from DiOTP's send reply
phone text not null, -- 10 digits, no +91
created_at timestamptz not null default now(),
consumed_at timestamptz -- set once, when it signs someone in
);
create index otp_requests_phone_created on public.otp_requests (phone, created_at desc);
-- Row level security on, and no policies: only the service role used by the
-- Edge Function can read or write this table. Browsers cannot.
alter table public.otp_requests enable row level security;The table binds each request_id to the phone it was sent to. The browser holds the request_id between the two steps, but it cannot change which phone a successful verify signs in, and it cannot reuse a request_id: the verify step consumes each row exactly once.
The Edge Function
One function handles both actions. It calls DiOTP over plain HTTPS with fetch, sends to as the 10-digit number without +91 and country_code as the integer 91, and adds an Idempotency-Key to every send so a retry after a timeout or a 503 cannot send a second code. Request and response fields are on the send OTP reference and the verify OTP reference.
supabase/functions/phone-otp/index.ts
// supabase/functions/phone-otp/index.ts
import { createClient } from 'jsr:@supabase/supabase-js@2'
const DIOTP = 'https://api-diotp.diorbit.com/v1'
const COOLDOWN_SECONDS = 30
const REQUEST_TTL_MINUTES = 10
// SUPABASE_URL and SUPABASE_SERVICE_ROLE_KEY are set in every Edge Function.
const admin = createClient(Deno.env.get('SUPABASE_URL')!, Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!, {
auth: { persistSession: false, autoRefreshToken: false },
})
const cors = {
'Access-Control-Allow-Origin': Deno.env.get('APP_ORIGIN') ?? '*',
'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
'Access-Control-Allow-Methods': 'POST, OPTIONS',
}
function json(body: unknown, status = 200, extra: Record<string, string> = {}) {
return new Response(JSON.stringify(body), {
status,
headers: { ...cors, 'Content-Type': 'application/json', ...extra },
})
}
type DiotpResult = { ok: true; data: any } | { ok: false; status: number; code: string }
async function diotp(path: string, body: unknown, idempotencyKey?: string): Promise<DiotpResult> {
const headers: Record<string, string> = {
Authorization: `Bearer ${Deno.env.get('DIOTP_API_KEY')}`,
'Content-Type': 'application/json',
}
if (idempotencyKey) headers['Idempotency-Key'] = idempotencyKey
try {
const res = await fetch(`${DIOTP}${path}`, {
method: 'POST', headers, body: JSON.stringify(body), signal: AbortSignal.timeout(10_000),
})
const data = await res.json().catch(() => ({}))
if (res.ok) return { ok: true, data }
return { ok: false, status: res.status, code: data?.error?.code ?? 'unknown' }
} catch {
return { ok: false, status: 0, code: 'network_error' }
}
}
// What the visitor sees for each DiOTP error code: [status, message, retry-after seconds].
const USER_ERRORS: Record<string, [number, string, number?]> = {
resend_cooldown: [429, 'Please wait 30 seconds before asking for another code.', 30],
phone_hourly_limit: [429, 'Too many codes for this number. Try again in an hour.', 3600],
phone_daily_limit: [429, 'Too many codes for this number today. Try tomorrow.'],
api_key_minute_limit: [429, 'We are busy right now. Please try again in a minute.', 60],
rate_limited: [429, 'We are busy right now. Please try again in a minute.', 60],
invalid_code: [400, 'That code is not right. Check the SMS and try again.'],
expired: [410, 'This code has expired. Ask for a new one.'],
not_pending: [409, 'This code is no longer valid. Ask for a new one.'],
not_found: [404, 'We could not find that code. Ask for a new one.'],
too_many_attempts: [429, 'Too many wrong tries. Ask for a new code.'],
invalid_request: [400, 'Enter a valid 10-digit mobile number.'],
}
function otpError(code: string, status: number) {
const known = USER_ERRORS[code]
if (!known) {
// unauthorized, trial_restricted, trial_used_up, insufficient_balance,
// account_suspended, channel_not_enabled, test_limit, sending_unavailable ...
console.error('DiOTP error', status, code) // never log the key
return json({ error: 'otp_unavailable', message: 'We could not send a code right now. Please try again shortly.' }, 503)
}
const [httpStatus, message, wait] = known
return wait
? json({ error: code, message, retry_after: wait }, httpStatus, { 'Retry-After': String(wait) })
: json({ error: code, message }, httpStatus)
}
function normalize(raw: unknown): string | null {
let d = String(raw ?? '').replace(/\D/g, '')
if (d.length === 12 && d.startsWith('91')) d = d.slice(2)
if (d.length === 11 && d.startsWith('0')) d = d.slice(1)
return /^[6-9]\d{9}$/.test(d) ? d : null
}
async function send(input: { phone?: string }) {
const phone = normalize(input.phone)
if (!phone) return json({ error: 'invalid_phone', message: 'Enter a 10-digit mobile number.' }, 400)
// Our own copy of the 30 second cooldown, shared by every device: no API call.
const since = new Date(Date.now() - COOLDOWN_SECONDS * 1000).toISOString()
const { data: recent } = await admin.from('otp_requests')
.select('created_at').eq('phone', phone).gt('created_at', since).limit(1)
if (recent?.length) return otpError('resend_cooldown', 429)
const body = { to: phone, country_code: 91, channel: 'sms', purpose: 'login' }
const key = crypto.randomUUID() // one key per user action, reused only for its retry
let result = await diotp('/otp/send', body, key)
if (!result.ok && (result.code === 'network_error' || result.code === 'sending_unavailable')) {
await new Promise((r) => setTimeout(r, 1500))
result = await diotp('/otp/send', body, key) // same key: no second code
}
if (!result.ok) return otpError(result.code, result.status)
const { error } = await admin.from('otp_requests').insert({ request_id: result.data.request_id, phone })
if (error) return json({ error: 'server_error' }, 500)
return json({ request_id: result.data.request_id, expires_at: result.data.expires_at, resend_in: COOLDOWN_SECONDS })
}
async function verify(input: { request_id?: string; code?: string }) {
const requestId = String(input.request_id ?? '')
const code = String(input.code ?? '').trim()
if (!requestId || !/^\d{4,10}$/.test(code)) {
return json({ error: 'invalid_code', message: 'Enter the code from the SMS.' }, 400)
}
const result = await diotp('/otp/verify', { request_id: requestId, code })
// already_verified is accepted only because the consume step below still
// refuses a request_id that has signed someone in before.
if (!result.ok && result.code !== 'already_verified') return otpError(result.code, result.status)
// Consume the request exactly once, and read the phone it was sent to.
const fresh = new Date(Date.now() - REQUEST_TTL_MINUTES * 60_000).toISOString()
const { data: row } = await admin.from('otp_requests')
.update({ consumed_at: new Date().toISOString() })
.eq('request_id', requestId).is('consumed_at', null).gt('created_at', fresh)
.select('phone').maybeSingle()
if (!row) return json({ error: 'already_used', message: 'This code was already used. Ask for a new one.' }, 409)
// Find or create the Supabase user for this phone number.
const email = `${row.phone}@${Deno.env.get('PHONE_EMAIL_DOMAIN')}`
const created = await admin.auth.admin.createUser({
email, email_confirm: true, phone: `91${row.phone}`, phone_confirm: true,
})
if (created.error && created.error.code !== 'email_exists') {
console.error('createUser failed', created.error.code)
return json({ error: 'server_error' }, 500)
}
// A one-time token the browser exchanges for a normal Supabase session.
// generateLink does not send any email.
const link = await admin.auth.admin.generateLink({ type: 'magiclink', email })
if (link.error) {
console.error('generateLink failed', link.error.code)
return json({ error: 'server_error' }, 500)
}
return json({ verified: true, token_hash: link.data.properties.hashed_token })
}
Deno.serve(async (req) => {
if (req.method === 'OPTIONS') return new Response('ok', { headers: cors })
if (req.method !== 'POST') return json({ error: 'method_not_allowed' }, 405)
const input = await req.json().catch(() => ({}))
if (input.action === 'send') return send(input)
if (input.action === 'verify') return verify(input)
return json({ error: 'unknown_action' }, 400)
})Terminal
# Secrets for the function (never in your front-end code)
supabase secrets set DIOTP_API_KEY=diotp_live_xxxxxxxx
supabase secrets set PHONE_EMAIL_DOMAIN=phone.your-domain.example
supabase secrets set APP_ORIGIN=https://app.your-domain.example
# Apply the table, then deploy. Visitors are not signed in yet when they ask
# for a code, so the function does its own checks instead of requiring a JWT.
supabase db push
supabase functions deploy phone-otp --no-verify-jwtSupabase users signed in through the Admin API need an email for generateLink, so the function gives each phone user a placeholder address such as 9876543210@phone.your-domain.example, marked as confirmed. Use a subdomain you own that receives no mail. generateLink only returns the token; it does not send an email. The user record also gets the phone number, confirmed, so user.phone reads as you expect.
If your project already has phone users from Supabase's built-in provider, createUser fails for them with a phone_exists error. Look those users up once and give them the placeholder email with updateUserById, then the function signs them in like everyone else.
Error codes and the 30 second cooldown
DiOTP returns errors as {"error":{"code":"...","message":"..."}}, and the code never changes. The function maps codes the visitor can act on to a plain message with the right status, adds Retry-After to rate limits, and hides account problems behind otp_unavailable while logging the code.
| Code | Status | What the function returns |
|---|---|---|
| resend_cooldown | 429 | Retry-After: 30. The function also checks its own table, so a second device gets the same answer without an API call. |
| phone_hourly_limit | 429 | Retry-After: 3600. Come back in an hour. |
| phone_daily_limit | 429 | Try tomorrow; 10 codes per number per day. |
| api_key_minute_limit, rate_limited | 429 | Retry-After: 60. |
| invalid_code | 400 | Try again, up to 5 attempts. |
| expired | 410 | Offer a new code; codes last 5 minutes. |
| too_many_attempts | 429 | Start over with a new code. |
| unauthorized, trial_restricted, trial_used_up, insufficient_balance, test_limit | 401, 402, 403, 429 | Logged; the visitor sees otp_unavailable. |
A 429 from DiOTP means nothing was sent and nothing was charged. Every code is listed on the error codes page.
Sign the user in from the browser
The front end calls the function through supabase.functions.invoke and, after a successful verify, passes the token_hash to supabase.auth.verifyOtp with type email. That call returns a session exactly like any other Supabase sign-in.
src/phone-login.ts
// src/phone-login.ts (browser, with supabase-js v2)
import { createClient, FunctionsHttpError } from '@supabase/supabase-js'
const supabase = createClient(import.meta.env.VITE_SUPABASE_URL, import.meta.env.VITE_SUPABASE_ANON_KEY)
type OtpError = { error: string; message?: string; retry_after?: number }
async function call<T>(body: Record<string, string>): Promise<T> {
const { data, error } = await supabase.functions.invoke('phone-otp', { body })
if (error) {
// Non-2xx replies arrive as FunctionsHttpError; the JSON body is on error.context.
const detail: OtpError = error instanceof FunctionsHttpError
? await error.context.json().catch(() => ({ error: 'unknown' }))
: { error: 'network_error' }
throw detail
}
return data as T
}
export async function sendCode(phone: string) {
// Returns { request_id, expires_at, resend_in }. On 429, read retry_after
// and count down on the resend button.
return call<{ request_id: string; expires_at: string; resend_in: number }>({ action: 'send', phone })
}
export async function verifyCode(requestId: string, code: string) {
const { token_hash } = await call<{ verified: true; token_hash: string }>({
action: 'verify', request_id: requestId, code,
})
// Exchange the one-time token for a normal Supabase session.
const { data, error } = await supabase.auth.verifyOtp({ token_hash, type: 'email' })
if (error) throw { error: 'session_error', message: error.message }
return data.session // the user is signed in; RLS sees auth.uid() as usual
}Show a resend button that is disabled for resend_in seconds after each send, and for retry_after seconds after any 429. That turns the cooldown into a countdown instead of an error message.
Trade-offs to accept before you choose this
- You do not use Supabase's built-in phone provider, so signInWithOtp({ phone }) and the Send SMS hook are not part of this flow. Your front end calls the Edge Function instead.
- Each phone user has a placeholder email. Do not show it, and do not send mail to it. If a user later adds a real email, update the record with updateUserById.
- Supabase's own auth rate limits and CAPTCHA protection apply to its auth endpoints, not to your function. DiOTP still limits each number (1 code every 30 seconds, 3 an hour, 10 a day) and each key (30 sends a minute), but add a bot check such as a CAPTCHA token verified inside the function on public sign-up forms. See SMS pumping protection.
- The function holds the service role key, which can do anything in your project. Keep it to these two actions and review changes to it carefully.
- Phone as a second factor (Supabase MFA) is a different feature and is not covered here.
In return you get OTP delivery to Indian numbers on DiOTP's registered DLT header with no DLT paperwork, codes that are generated and checked outside your database, and ordinary Supabase sessions for everything else in your app.
Test it
Run the function locally with supabase functions serve phone-otp --no-verify-jwt --env-file supabase/functions/.env and call it from your app. A new DiOTP account has 10 free test messages, sent only to the mobile number you verified at sign-up; other numbers return 403 trial_restricted, which the function reports as otp_unavailable and logs. Ask twice within 30 seconds to see resend_cooldown, verify the same request twice to see already_used, and wait more than 5 minutes to see expired. Recharge your wallet from ₹100 to send to any Indian mobile number at ₹0.26 to ₹0.40 per OTP plus 18% GST.
Send OTP reference Verify OTP reference Error codes
OTP without DLT React and Next.js OTP guide OTP security best practices
