Build an SMS demo
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:
01<!-- 1. Install Magic SDK -->
02<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:
01/* 2. Initialize Magic Instance */
02const 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:
#3. Implement Render Function
Let's add the logic on what should display when:
- Users are not logged in,
- Users are logged in, and
Copy and paste this code:
01/* 3. Implement Render Function */
02const render = async () => {
03 const isLoggedIn = await magic.user.isLoggedIn();
04
05 /* Show login form if user is not logged in */
06 let html = `
07 <h1>Please sign up or login</h1>
08 <form onsubmit="handleLogin(event)">
09 <input type="phonenumber" name="phone" required="required" placeholder="Enter your phonenumber" />
10 <button type="submit">Send</button>
11 </form>
12 `;
13
14 if (isLoggedIn) {
15 /* Get user metadata including phone */
16 const userMetadata = await magic.user.getMetadata();
17 html = `
18 <h1>Current user: ${userMetadata.phoneNumber}</h1>
19 <button onclick="handleLogout()">Logout</button>
20 `;
21 }
22
23 document.getElementById('app').innerHTML = html;
24};
#4. Implement Login Handler
You can now implement user login without needing to write any backend code! Copy and paste this code:
01const handleLogin = async e => {
02 e.preventDefault();
03 const phoneNumber = new FormData(e.target).get('phone');
04 if (phoneNumber) {
05 /* One-liner login 🤯 */
06 await magic.auth.loginWithSMS({ phoneNumber });
07 render();
08 }
09};
#5. Implement Logout Handler
To wrap it up, let's implement user logout as well. Copy and paste this code:
01/* 5. Implement Logout Handler */
02const handleLogout = async () => {
03 await magic.user.logout();
04 render();
05};
#6. Done
You've completed the tutorial! Here's a working demo of the tutorial we just went over.