Aller au contenu

Authentification Stytch avec Hono ​

Cet exemple montre comment configurer une application full-stack avec les SDK frontend Stytch et un backend Hono sur Cloudflare Workers, avec vite et react.

Une application complète suivant ces principes est disponible ici.

Installation ​

sh
# Backend
npm install @hono/stytch-auth stytch

# Frontend
npm install @stytch/react @stytch/vanilla-js
sh
# Backend
yarn add @hono/stytch-auth stytch

# Frontend
yarn add @stytch/react @stytch/vanilla-js
sh
# Backend
pnpm add @hono/stytch-auth stytch

# Frontend
pnpm add @stytch/react @stytch/vanilla-js
sh
# Backend
bun add @hono/stytch-auth stytch

# Frontend
bun add @stytch/react @stytch/vanilla-js

Configuration ​

  1. Créez un compte Stytch et sélectionnez Consumer Authentication.
  2. Activez le Frontend SDK dans Configuration.
  3. Récupérez vos identifiants dans Project Settings.

Variables d’environnement ​

Placez les variables d’environnement des Workers backend dans .dev.vars, et celles de Vite frontend dans .env.local.

Plain
STYTCH_PROJECT_ID=project-live-xxx
STYTCH_PROJECT_SECRET=secret-live-xxx
Plain
VITE_STYTCH_PUBLIC_TOKEN=public-token-live-xxx

Frontend ​

  1. Entourez votre application du composant <StytchProvider /> et transmettez-lui une instance de Stytch UI Client.
  2. Utilisez le composant <StytchLogin /> pour connecter l’utilisateur. Consultez le bac à sable de composants pour voir les méthodes d’authentification et les personnalisations de style disponibles.
  3. Une fois l’utilisateur connecté, le hook useStytchUser() permet de récupérer les données de l’utilisateur actif.
  4. Les informations de session de l’utilisateur sont automatiquement stockées dans un cookie et transmises à votre backend.
tsx
import React from 'react'
import {StytchUIClient} from '@stytch/vanilla-js';
import {StytchProvider, useStytchUser} from '@stytch/react';
import LoginPage from './LoginPage'
import Dashboard from './Dashboard'

const stytch = new StytchUIClient(import.meta.env.VITE_STYTCH_PUBLIC_TOKEN ?? '');

function AppContent() {
  const { user, isInitialized } = useStytchUser()

  if (!isInitialized) return <div>Loading...</div>
  return user ? <Dashboard /> : <LoginPage />
}

function App() {
  return (
    <StytchProvider stytch={stytch}>
      <AppContent />
    </StytchProvider>
  )
}

export default App
tsx
import React from 'react'
import { StytchLogin } from '@stytch/react'
import { Products, OTPMethods } from '@stytch/vanilla-js'

const loginConfig = {
  products: [Products.otp],
  otpOptions: {
    expirationMinutes: 10,
    methods: [OTPMethods.Email],
  },
}

const LoginPage = () => {
  return <StytchLogin config={loginConfig} />
}

export default LoginPage
tsx
import React from 'react'
import { useStytchUser, useStytch } from '@stytch/react'

const Dashboard = () => {
  const { user } = useStytchUser()
  const stytchClient = useStytch()

  const handleLogout = () => stytchClient.session.revoke()

  return (
    <div style={{ maxWidth: '600px', margin: '2rem auto' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between' }}>
        <h1>Dashboard</h1>
        <button onClick={handleLogout}>Logout</button>
      </div>
      <p>Welcome, {user.emails[0]?.email}!</p>
    </div>
  )
}

export default Dashboard

Backend ​

  1. Protégez les points de terminaison avec un middleware Consumer.authenticateSessionLocal() pour authentifier le JWT de session Stytch.
  2. Utilisez la méthode Consumer.getStytchSession(c) pour récupérer les informations de session Stytch dans une route.
  3. Les routes qui nécessitent l’objet utilisateur complet peuvent utiliser la méthode Consumer.authenticateSessionRemote() pour effectuer un appel réseau aux serveurs Stytch.
src/index.ts
ts
import { Hono } from 'hono'
import { Consumer } from '@hono/stytch-auth'

const app = new Hono()

// Public route
app.get('/health', (c) => c.json({ status: 'ok' }))

// Protected route with local authentication (very fast)
app.get('/api/local', Consumer.authenticateSessionLocal(), (c) => {
  const session = Consumer.getStytchSession(c)
  return c.json({
    message: 'Protected data',
    sessionId: session.session_id,
  })
})

// Protected route with remote authentication & full user data
app.get('/api/remote', Consumer.authenticateSessionRemote(), (c) => {
  const session = Consumer.getStytchSession(c)
  const user = Consumer.getStytchUser(c)
  return c.json({
    message: 'Protected data',
    sessionId: session.session_id,
    firstName: user.name.first_name,
  })
})

export default app

Étapes suivantes ​

Documentation et ressources supplémentaires :

Les fonctions B2B pour les entreprises, comme la gestion des organisations, RBAC et SSO, vous intéressent ? Consultez la gamme Stytch B2B Authentication.

Participez aux discussions, posez vos questions et proposez des fonctionnalités dans la communauté Slack Stytch.

Publié sous licence MIT.