# Phone Login (SMS)

Authenticate users with their phone number using SMS one-time passcodes (OTP). This provides a secure, passwordless login experience.

## Request OTP

Call `requestPhoneOtp()` to send a one-time passcode to the user's phone number:

:::code-group

```tsx [auth.tsx]
import openfort from "./openfortConfig"

async function requestOtp(phoneNumber: string) {
  await openfort.auth.requestPhoneOtp({ phoneNumber });

  console.log('OTP sent to phone');
}
```

```ts [openfortConfig.ts]
import { Openfort } from '@openfort/openfort-js';

const openfort = new Openfort({
  baseConfiguration: {
    publishableKey: "YOUR_OPENFORT_PUBLISHABLE_KEY",
  }
});

export default openfort;
```

:::

## Log in with OTP

Call `logInWithPhoneOtp()` with the phone number and the OTP code the user received:

:::code-group

```tsx [auth.tsx]
import openfort from "./openfortConfig"

async function logInWithPhone(phoneNumber: string, otp: string) {
  const result = await openfort.auth.logInWithPhoneOtp({
    phoneNumber: phoneNumber,
    otp: otp
  });

  console.log('User logged in:', result.user.id);
}
```

```ts [openfortConfig.ts]
import { Openfort } from '@openfort/openfort-js';

const openfort = new Openfort({
  baseConfiguration: {
    publishableKey: "YOUR_OPENFORT_PUBLISHABLE_KEY",
  }
});

export default openfort;
```

```json [response.json]
{
  "token": "eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCJ9...",
  "user": {
    "id": "usr_cc9ed2b7-c5f5-4c43-8dca-c4b104ba1762",
    "createdAt": "2024-03-20T12:00:00Z",
    "updatedAt": "2024-03-20T12:00:00Z"
  }
}
```

:::

## Example implementation

Here's a complete example of a phone authentication flow:

```tsx
import openfort from "./openfortConfig";
import { useState } from "react";

function PhoneAuth() {
  const [phoneNumber, setPhoneNumber] = useState('');
  const [otp, setOtp] = useState('');
  const [step, setStep] = useState<'phone' | 'otp'>('phone');

  const handleRequestOtp = async () => {
    await openfort.auth.requestPhoneOtp({ phoneNumber });
    setStep('otp');
  };

  const handleVerifyOtp = async () => {
    const result = await openfort.auth.logInWithPhoneOtp({
      phoneNumber,
      otp
    });
    console.log('Logged in:', result.user.id);
  };

  if (step === 'phone') {
    return (
      <div>
        <input
          type="tel"
          value={phoneNumber}
          onChange={(e) => setPhoneNumber(e.target.value)}
          placeholder="+1234567890"
        />
        <button onClick={handleRequestOtp}>
          Send OTP
        </button>
      </div>
    );
  }

  return (
    <div>
      <input
        type="text"
        value={otp}
        onChange={(e) => setOtp(e.target.value)}
        placeholder="Enter OTP"
      />
      <button onClick={handleVerifyOtp}>
        Verify
      </button>
    </div>
  );
}
```
