magic-js icon indicating copy to clipboard operation
magic-js copied to clipboard

PromiEvent never resolves for auth methods in Next.js while working in plain HTML

Open nhussein11 opened this issue 1 year ago • 2 comments

✅ Prerequisites

  • [x] Did you perform a cursory search of open issues? Is this bug already reported elsewhere?
  • [x] Are you running the latest SDK version?
  • [x] Are you reporting to the correct repository (magic-sdk)?

🐛 Description

When using Magic SDK in a Next.js application, magic.auth.loginWithEmailOTP() hangs indefinitely. The promise remains in a pending state and never resolves or rejects. No Magic UI modal appears, no email is sent, and no errors are thrown.

Interestingly, the same configuration works perfectly in a plain HTML file, suggesting this is a Next.js-specific integration issue.

🧩 Steps to Reproduce

  1. Create a Next.js application with App Router
  2. Install magic-sdk version 31.0.0
  3. Create a React component with Magic SDK initialized using useRef and useEffect
  4. Configure Magic with custom network settings (Moonbase Alpha testnet)
  5. Add allowed origins in Magic Dashboard (including http://localhost:3000)
  6. Call magic.auth.loginWithEmailOTP({ email, showUI: true })
  7. Observe that the promise never resolves

🤔 Expected behavior

  1. Magic's authentication UI modal/iframe should appear
  2. User should be able to enter their email
  3. OTP should be sent to the provided email
  4. User enters OTP in Magic's UI
  5. Promise resolves with authentication token/result
  6. User is successfully authenticated

😮 Actual behavior

  • Promise remains in pending state indefinitely
  • No Magic UI modal/iframe appears in the DOM
  • No email is sent
  • No errors are thrown or logged
  • Console shows promise with [[PromiseState]]: "pending" that never changes
  • Button loading state never completes

Console Output:

Initializing Magic SDK...
Magic SDK initialized: r {endpoint: 'https://auth.magic.link', parameters: '...', networkHash: '...', testMode: false, ...}
Checking login status...
Starting login process for email: [email protected]
Calling loginWithEmailOTP...
didToken Promise {<pending>}

The promise object shows it's a PromiEvent with event listeners but remains pending forever.

💻 Code Sample

Next.js Component (NOT WORKING):

'use client';

import React, { useState, useEffect, useRef } from 'react';
import { Magic } from 'magic-sdk';

export const ConnectWallet = () => {
  const [email, setEmail] = useState('');
  const [isLoggedIn, setIsLoggedIn] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const magicRef = useRef<Magic | null>(null);

  useEffect(() => {
    if (typeof window !== 'undefined' && !magicRef.current) {
      magicRef.current = new Magic('MY_MAGIC_PK', {
        network: {
          rpcUrl: 'https://rpc.api.moonbase.moonbeam.network/',
          chainId: 1287,
        },
      });
    }
  }, []);

  const login = async () => {
    if (!magicRef.current) return;
    
    setIsLoading(true);
    try {
      // This hangs indefinitely
      const didToken = await magicRef.current.auth.loginWithEmailOTP({ 
        email,
        showUI: true 
      });
      
      console.log('didToken', didToken);
      
      if (didToken) setIsLoggedIn(true);
    } catch (error) {
      console.error('Login failed:', error);
    } finally {
      setIsLoading(false);
    }
  };

  const logout = async () => {
    if (!magicRef.current) return;
    await magicRef.current.user.logout();
    setIsLoggedIn(false);
    setEmail('');
  };

  if (isLoggedIn) {
    return (
      <div className="flex flex-col items-center gap-3">
        <div className="text-sm font-medium text-green-600">Wallet Connected</div>
        <button onClick={logout}>Disconnect</button>
      </div>
    );
  }

  return (
    <div className="flex flex-col items-center gap-3">
      <input
        type="email"
        placeholder="Enter your email"
        value={email}
        onChange={(e) => setEmail(e.target.value)}
        disabled={isLoading}
      />
      <button
        onClick={login}
        disabled={!email || isLoading}
      >
        {isLoading ? 'Connecting...' : 'Connect Wallet'}
      </button>
    </div>
  );
};

Plain HTML Implementation (WORKING):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Magic SDK Test</title>
</head>
<body>
    <form id="loginForm">
        <input type="email" id="email" required placeholder="Enter your email">
        <button type="submit" id="loginBtn">Login with Magic</button>
    </form>
    <div id="status"></div>

    <script src="https://unpkg.com/magic-sdk@latest/dist/magic.js"></script>
    <script>
        const magic = new Magic('MY_MAGIC_PK', {
            network: {
                rpcUrl: 'https://rpc.api.moonbase.moonbeam.network/',
                chainId: 1287,
            },
        });

        document.getElementById('loginForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            const email = document.getElementById('email').value.trim();

            try {
                // This works perfectly!
                const handle = await magic.auth.loginWithEmailOTP({
                    email,
                    showUI: true,
                });

                document.getElementById('status').textContent = `Login successful! Handle: ${handle}`;
                console.log('Login successful:', handle);
            } catch (error) {
                console.error('Login error:', error);
                document.getElementById('status').textContent = `Login failed: ${error.message}`;
            }
        });
    </script>
</body>
</html>

Magic Dashboard Configuration:

Allowed Origins & Redirects:
- https://localhost:3000
- http://localhost:3000
- http://127.0.0.1:3000

Troubleshooting Attempted:

  • ✅ Tried magic.wallet.connectWithUI() instead of loginWithEmailOTP()
  • ✅ Tried with and without showUI: true
  • ✅ Ensured Magic instance created only once with useRef
  • ✅ Added 'use client' directive (Next.js 13+ App Router)
  • ✅ Tried dynamic import with ssr: false
  • ✅ Checked Network tab - no failed requests
  • ✅ Checked console - no CSP or iframe errors
  • ✅ Verified allowed origins in Magic Dashboard

🌎 Environment

Software Version(s)
magic-sdk 31.0.0
Browser Tested on Brave and Chrome
Next.js 15.1.2
Operating System macOS

nhussein11 avatar Oct 14 '25 22:10 nhussein11

I do see that the property magic.overlay.isReadyForRequest is set to false. Is this something that might be involved with my problem?

Image

nhussein11 avatar Oct 19 '25 22:10 nhussein11

Also, after analyzing the iframe html loaded elements, I get to see some weird error messages:

Image

nhussein11 avatar Oct 19 '25 23:10 nhussein11