Esc

Authenticate

Authenticate a user with your server. Learn more

import { mega } from '@megaeth-labs/wallet-sdk';

const auth = await mega.authenticate();

if (auth.status === 'success' && auth.jwt) {
    // Send the token to your server to verify and start your own session.
    await fetch('/api/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ token: auth.jwt }),
    });
}
Runs on testnet with your wallet
ts
interface AuthenticateResponse {
    status: 'success' | 'cancelled' | 'error';
    error?: string;
    jwt?: string;
}
tsserver.ts
// Your app's host as the browser sees it: no scheme, and any port included.
const APP_HOST = 'app.example.com';

// POST /api/login
export async function login(request: Request): Promise<Response> {
    const { token } = await request.json();

    const url = new URL('https://wallet-api.megaeth.com/v1/partner-auth/verify');
    url.searchParams.set('origin', APP_HOST);
    url.searchParams.set('token', token);

    // Fails when the token is invalid, has expired or was issued for a different host.
    const response = await fetch(url);
    if (!response.ok) return new Response('Unauthorised', { status: 401 });

    const { walletAddress } = await response.json();

    // Issue your own session for walletAddress, for example a cookie.
    return Response.json({ walletAddress });
}