Authentication and Permissions
Magic Code Auth
Instant supports a "magic-code" flow for auth. Users provide their email, we send them a login code on your behalf, and they authenticate with your app.
Choose the platform you're building for to see a full example.
#Full Magic Code Example
Here's a full example of magic code auth with vanilla JavaScript. Open up your src/main.ts file, and replace the entirety of it with the following code:
import { init, type User } from '@instantdb/core';const APP_ID = '__APP_ID__';const db = init({ appId: APP_ID });const app = document.getElementById('app')!;let sentEmail = '';function renderApp(user: User | undefined) {if (user) {renderMain(user);} else {renderLogin();}}function renderMain(user: User) {app.innerHTML = `<div><h1>Hello ${user.email}!</h1><button id="sign-out">Sign out</button></div>`;document.getElementById('sign-out')!.addEventListener('click', () => {db.auth.signOut();});}function renderLogin() {if (!sentEmail) {renderEmailStep();} else {renderCodeStep();}}function renderEmailStep() {app.innerHTML = `<div><h2>Let's log you in</h2><p>Enter your email, and we'll send you a verification code.We'll create an account for you too if you don't already have one.</p><form id="email-form"><inputid="email-input"type="email"placeholder="Enter your email"required/><button type="submit">Send Code</button></form></div>`;document.getElementById('email-form')!.addEventListener('submit', (e) => {e.preventDefault();const email = (document.getElementById('email-input') as HTMLInputElement).value;sentEmail = email;renderLogin();db.auth.sendMagicCode({ email }).catch((err) => {alert('Uh oh: ' + err.body?.message);sentEmail = '';renderLogin();});});}function renderCodeStep() {app.innerHTML = `<div><h2>Enter your code</h2><p>We sent an email to <strong>${sentEmail}</strong>.Check your email, and paste the code you see.</p><form id="code-form"><inputid="code-input"type="text"placeholder="123456..."required/><button type="submit">Verify Code</button></form></div>`;document.getElementById('code-form')!.addEventListener('submit', (e) => {e.preventDefault();const codeInput = document.getElementById('code-input') as HTMLInputElement;const code = codeInput.value;db.auth.signInWithMagicCode({ email: sentEmail, code }).catch((err) => {alert('Uh oh: ' + err.body?.message);codeInput.value = '';});});}db.subscribeAuth((auth) => {renderApp(auth.user);});
Make sure you have a <div id="app"></div> element in your HTML.
Let's dig deeper.
We created a login flow to handle magic code auth. Of note is auth.sendMagicCode and auth.signInWithMagicCode.
On successful validation, Instant's backend will return a user object with a refresh token. The client SDK will then restart the websocket connection with Instant's sync layer and provide the refresh token.
When doing queries or transactions, the refresh token will be used to hydrate auth on the backend during permission checks.
On the client, auth will now be populated with a user -- huzzah!
#Send a Magic Code
db.auth.sendMagicCode({ email }).catch((err) => {alert('Uh oh :' + err.body?.message);onSendEmail('');});
Use auth.sendMagicCode to generate a magic code on instant's backend and email it to the user.
#Sign in with Magic Code
db.auth.signInWithMagicCode({ email: sentEmail, code }).catch((err) => {inputEl.value = '';alert('Uh oh :' + err.body?.message);});
You can then use auth.signInWithMagicCode to authenticate the user with the magic code they provided.
#Setting properties at signup
Pass extraFields to signInWithMagicCode to set custom $users properties when a user is first created. Fields are only written on first signup; returning users are unaffected.
const { user, created } = await db.auth.signInWithMagicCode({email: sentEmail,code,extraFields: { nickname: 'nezaj' },});if (created) {// Scaffold default data for new usersdb.transact([db.tx.settings[id()].update({ theme: 'light' }).link({ user: user.id }),]);}
The fields must be defined as optional attributes on $users in your schema. A create rule on $users is also required. See Setting properties at signup for the full guide.
#Test users
If you need to create a user with a pre-defined code for app store review or testing, you can assign a magic code to an email from the Auth page of the Dashboard.
When a test user signs in, they can use the static code instead of receiving the code an email. The static code will never expire and will always be valid until it is deleted from the dashboard.