Build an SMS demo

A Hello World tutorial to quickly get familiar with Magic. 🚀

A Hello World tutorial to quickly get familiar with Magic. 🚀

👉 What you'll build: SMS Hello World demo


Get Started

0. Get the template code

To follow along with the tutorial, use our SMS Hello World template in CodeSandBox.

1. Install Magic SDK

Install the Magic SDK to the SMS Hello World template with a script tag. You can copy and paste the below code to the CodeSandBox editor after the comment:

<!-- 1. Install Magic SDK --> <script src="https://auth.magic.link/sdk"></script>

Or install Magic SDK with yarn or npm.

2. Initialize Magic Instance

Initialize a Magic instance with a Publishable API Key with this code:

/* 2. Initialize Magic Instance */ const magic = new Magic('YOUR_LIVE_PUBLISHABLE_API_KEY');

You need to sign up to Magic Dashboard to get your own API keys.

Replace the 'YOUR_LIVE_PUBLISHABLE_API_KEY' string with your "Publishable API Key" from the Magic Dashboard:

dashboard-pk.png

3. Implement Render Function

Let's add the logic on what should display when:

  1. Users are not logged in,
  2. Users are logged in, and

Copy and paste this code:

/* 3. Implement Render Function */ const render = async () => { const isLoggedIn = await magic.user.isLoggedIn(); /* Show login form if user is not logged in */ let html = ` <h1>Please sign up or login</h1> <form onsubmit="handleLogin(event)"> <input type="phonenumber" name="phone" required="required" placeholder="Enter your phonenumber" /> <button type="submit">Send</button> </form> `; if (isLoggedIn) { /* Get user metadata including phone */ const userMetadata = await magic.user.getMetadata(); html = ` <h1>Current user: ${userMetadata.phoneNumber}</h1> <button onclick="handleLogout()">Logout</button> `; } document.getElementById('app').innerHTML = html; };

4. Implement Login Handler

You can now implement user login without needing to write any backend code! Copy and paste this code:

const handleLogin = async e => { e.preventDefault(); const phoneNumber = new FormData(e.target).get('phone'); if (phoneNumber) { /* One-liner login 🤯 */ await magic.auth.loginWithSMS({ phoneNumber }); render(); } };

5. Implement Logout Handler

To wrap it up, let's implement user logout as well. Copy and paste this code:

/* 5. Implement Logout Handler */ const handleLogout = async () => { await magic.user.logout(); render(); };

6. Done

You've completed the tutorial! Here's a working demo of the tutorial we just went over.

Ready to integrate ?

Integrate Magic with your existing client.