### Go Full Example Setup Source: https://stytch.com/docs/llms-full.txt A complete Go HTTP server setup demonstrating Stytch integration for magic link authentication. ```go package main import ( "bytes" "encoding/json" "net/http" "os" ) func main() { http.HandleFunc("/login", sendLoginHandler) http.HandleFunc("/authenticate", authenticateHandler) http.HandleFunc("/dashboard", dashboardHandler) http.ListenAndServe(":3000", nil) } // Implement sendLoginHandler/authenticateHandler/dashboardHandler using the // requests shown above. ``` -------------------------------- ### Full Stytch B2B Authentication Example Source: https://stytch.com/docs/multi-tenant-auth/build-auth/custom/via-api A complete example demonstrating the setup and usage of Stytch B2B authentication, including API client instantiation, environment variable loading, and HTTP handler registration. ```go package main import ( "context" "fmt" "log" "net/http" "os" gorillaSessions "github.com/gorilla/sessions" "github.com/joho/godotenv" "github.com/stytchauth/stytch-go/v15/stytch/b2b/b2bstytchapi" "github.com/stytchauth/stytch-go/v15/stytch/b2b/discovery/intermediatesessions" discoveryOrgs "github.com/stytchauth/stytch-go/v15/stytch/b2b/discovery/organizations" "github.com/stytchauth/stytch-go/v15/stytch/b2b/magiclinks/discovery" emlDiscovery "github.com/stytchauth/stytch-go/v15/stytch/b2b/magiclinks/email/discovery" "github.com/stytchauth/stytch-go/v15/stytch/b2b/organizations" "github.com/stytchauth/stytch-go/v15/stytch/b2b/sessions" ) var ctx = context.Background() const sessionKey = "stytch_session_token" func main() { // Load variables from .env file into the environment. if err := godotenv.Load(".env.local"); err != nil { log.Fatalf("Error loading .env file: %v", err) } // Instantiate a new API service. service := NewAuthService( os.Getenv("STYTCH_PROJECT_ID"), os.Getenv("STYTCH_SECRET"), ) // Register HTTP handlers. mux := http.NewServeMux() mux.HandleFunc("/", service.indexHandler) mux.HandleFunc("/login", service.sendMagicLinkHandler) ``` -------------------------------- ### Go: Full Application Setup Example Source: https://stytch.com/docs/consumer-auth/build-auth/custom/via-api This is a basic structure for a Go application demonstrating how to set up HTTP handlers for login, authentication, and protected dashboard routes. ```Go package main import ( "bytes" "encoding/json" "net/http" "os" ) func main() { http.HandleFunc("/login", sendLoginHandler) http.HandleFunc("/authenticate", authenticateHandler) http.HandleFunc("/dashboard", dashboardHandler) http.ListenAndServe(":3000", nil) } // Implement sendLoginHandler/authenticateHandler/dashboardHandler using the // requests shown above. ``` -------------------------------- ### OAuth Google Start Source: https://stytch.com/docs/api-reference/consumer/frontend-sdks/vanilla-js/methods/oauth/start Starts the OAuth flow for Google. This example demonstrates how to configure redirect URLs, custom scopes, and provider parameters. ```APIDOC ## oauth.google.start() ### Description Starts the OAuth flow for Google by redirecting the browser to Stytch's OAuth start endpoint. It automatically generates and stores a PKCE `code_verifier`. ### Method `stytch.oauth.google.start(options)` ### Parameters #### Request Body - **login_redirect_url** (string) - Required - The URL Stytch redirects to after the OAuth flow is completed for an existing user. Must be configured as a Login URL in the Redirect URL page. - **signup_redirect_url** (string) - Required - The URL Stytch redirects to after the OAuth flow is completed for a new user. Must be configured as a Signup URL in the Redirect URL page. - **custom_scopes** (string[]) - Optional - A list of custom scopes to include. These must be URL encoded. - **provider_params** (object) - Optional - An object containing parameters to pass to the OAuth provider (e.g., `login_hint`). Consult the OAuth provider's documentation for supported parameters. - **oauth_attach_token** (string) - Optional - A single-use token for connecting Stytch User selection from an OAuth Attach request to the corresponding OAuth Start request. ### Request Example ```javascript import { StytchClient } from '@stytch/vanilla-js'; const stytch = new StytchClient('YOUR_PUBLIC_TOKEN'); stytch.oauth.google.start({ login_redirect_url: 'YOUR_APP_URL/authenticate', signup_redirect_url: 'YOUR_APP_URL/authenticate', custom_scopes: [ 'https://www.googleapis.com/auth/documents.readonly', 'https://www.googleapis.com/auth/drive.readonly', ], provider_params: { login_hint: 'example_hint@stytch.com', }, }); ``` ### Response This method initiates a browser redirect and does not return a response directly in the SDK. The outcome of the OAuth flow is handled at the `redirect_url`. ``` -------------------------------- ### Full Completed Example: Node.js Stytch Integration Source: https://stytch.com/docs/llms-full.txt A complete Node.js example demonstrating Stytch email magic link authentication, including Express setup, login, authentication callback, and session protection. ```javascript const express = require('express'); const session = require('express-session'); const stytch = require('stytch'); const app = express(); app.use(express.json()); app.use(session({ resave: true, saveUninitialized: false, secret: 'session-signing-secret', })); const stytchClient = new stytch.Client({ project_id: process.env.STYTCH_PROJECT_ID, secret: process.env.STYTCH_SECRET, }); app.post('/login', async (req, res) => { const params = { email: req.body.email, login_magic_link_url: "http://localhost:3000/authenticate", signup_magic_link_url: "http://localhost:3000/authenticate", }; const resp = await stytchClient.magicLinks.email.loginOrCreate(params); res.json(resp); }); ``` -------------------------------- ### Initialize Stytch Client and Login Route Source: https://stytch.com/docs/multi-tenant-auth/build-auth/custom/via-api Initialize the Stytch client using environment variables and set up a Flask route for the login/signup flow. This example demonstrates basic setup for handling user email input. ```python import os import dotenv from flask import Flask, request, redirect, session, url_for from stytch import B2BClient from stytch.core.response_base import StytchError # load the .env file dotenv.load_dotenv() ``` -------------------------------- ### Install Next.js Package Source: https://stytch.com/docs/api-reference/consumer/frontend-sdks/nextjs/installation Install the Stytch Next.js package using npm. ```bash npm install @stytch/nextjs ``` -------------------------------- ### Install Stytch Next.js SDK Source: https://stytch.com/docs/consumer-auth/authentication/otps/sdk Install the Stytch Next.js SDK using npm or yarn. ```bash npm install @stytch/nextjs ``` ```bash yarn add @stytch/nextjs ``` -------------------------------- ### Install Stytch Vanilla JS SDK Source: https://stytch.com/docs/api-reference/consumer/frontend-sdks/vanilla-js/installation Install the `@stytch/vanilla-js` package using npm. ```bash npm install @stytch/vanilla-js ``` -------------------------------- ### Get M2M Client Response Source: https://stytch.com/docs/llms-full.txt Example response from the Get M2M Client endpoint. The `next_client_secret_last_four` field indicates if a rotation is in progress. ```javascript { "m2m_client": { "client_description": "Following the Stytch guide.", "client_id": "m2m-client-test-a50053...", "client_name": "Example client", "client_secret_last_four": "QqNU", "next_client_secret_last_four": null, "scopes": [ "read:settings", "update:settings" ], "status": "active", "trusted_metadata": { "billing_tier": "standard", "api_version": "v2" } }, "request_id": "request-id-test-c50eb06f-69b4-41be-8640-0d9fd2f561ae", "status_code": 200 } ``` -------------------------------- ### Install Stytch Go SDK Source: https://stytch.com/docs/multi-tenant-auth/build-auth/custom/via-api Use this command to install the Stytch Go SDK. Ensure you are using the correct version. ```go go get github.com/stytchauth/stytch-go/v16 ``` -------------------------------- ### Example Response for Get Connected Apps Source: https://stytch.com/docs/api-reference/consumer/frontend-sdks/nextjs/methods/connected-apps/get-connected-apps This is an example of the JSON response structure returned by the `getConnectedApps` method, detailing the properties of a connected application. ```json { "status_code": 200, "request_id": "request-id-test-b05c992f-ebdc-489d-a754-c7e70ba13141", "connected_apps": [ { "client_type": "first_party", "connected_app_id": "connected-app-test-aeadeabc-a3a3-4796-83d0-b757e3001000", "description": "A first party connected app", "logo_url": null, "name": "first-party-confidential-app", "scopes_granted": "openid profile email" } ] } ``` -------------------------------- ### Initialize Stytch Client and Set Up Login Route Source: https://stytch.com/docs/multi-tenant-auth/build-auth/custom/via-api Initializes the Stytch client with project credentials and registers an HTTP handler for the /login route to initiate the magic link flow. ```Go package main import ( "context" "fmt" "log" "net/http" "os" gorillaSessions "github.com/gorilla/sessions" "github.com/joho/godotenv" "github.com/stytchauth/stytch-go/v16/stytch/b2b/b2bstytchapi" discoveryOrgs "github.com/stytchauth/stytch-go/v16/stytch/b2b/discovery/organizations" "github.com/stytchauth/stytch-go/v16/stytch/b2b/magiclinks/discovery" emlDiscovery "github.com/stytchauth/stytch-go/v16/stytch/b2b/magiclinks/email/discovery" ) var ctx = context.Background() const sessionKey = "stytch_session_token" func main() { // Load variables from .env file into the environment. if err := godotenv.Load(".env.local"); err != nil { log.Fatalf("Error loading .env file: %v", err) } // Instantiate a new API service. service := NewAuthService( os.Getenv("STYTCH_PROJECT_ID"), os.Getenv("STYTCH_SECRET"), ) // Register HTTP handlers. mux := http.NewServeMux() mux.HandleFunc("/login", service.sendMagicLinkHandler) // Start server. server := http.Server{ Addr: ":3000", Handler: mux, } log.Println("WARNING: For testing purposes only. Not intended for production use...") log.Println("Starting server on http://localhost:3000") if err := server.ListenAndServe(); err != nil { log.Fatal(err) } } type AuthService struct { client *b2bstytchapi.API store *gorillaSessions.CookieStore } func NewAuthService(projectId, secret string) *AuthService { client, err := b2bstytchapi.NewClient(projectId, secret) if err != nil { log.Fatalf("Error creating client: %v", err) } return &AuthService{ client: client, store: gorillaSessions.NewCookieStore([]byte("your-secret-key")), } } func (s *AuthService) sendMagicLinkHandler(w http.ResponseWriter, r *http.Request) { if err := r.ParseForm(); err != nil { log.Printf("Error parsing form: %v\n", err) http.Error(w, err.Error(), http.StatusInternalServerError) return } email := r.Form.Get("email") if email == "" { http.Error(w, "Email is required", http.StatusBadRequest) return } _, err := s.client.MagicLinks.Email.Discovery.Send( ctx, &emlDiscovery.SendParams{ EmailAddress: email, }) if err != nil { log.Printf("Error sending email: %v\n", err) http.Error(w, err.Error(), http.StatusInternalServerError) return } w.WriteHeader(http.StatusOK) fmt.Fprintln(w, "Successfully sent magic link email!") } ``` -------------------------------- ### Password Reset by Email Start API Response Source: https://stytch.com/docs/api-reference/consumer/frontend-sdks/nextjs/methods/passwords/reset-by-email-start This is an example of a successful response from the Reset By Email Start API endpoint. It includes status codes, request IDs, and user/email identifiers. ```json { "status_code": 200, "request_id": "request-id-test-b05c992f-ebdc-489d-a754-c7e70ba13141", "user_id": "user-test-16d9ba61-97a1-4ba4-9720-b03761dc50c6", "email_id": "email-test-81bf03a8-86e1-4d95-bd44-bb3495224953" } ``` -------------------------------- ### Start WebAuthn Registration with Passkey Options Source: https://stytch.com/docs/consumer-auth/authentication/passkeys/overview Call this endpoint to initiate the WebAuthn registration process and retrieve options for Passkey credential creation. Ensure `return_passkey_credential_options` is set to true. ```bash curl --request POST \ --url https://test.stytch.com/v1/webauthn/register/start \ -u 'PROJECT_ID:SECRET' \ -H 'Content-Type: application/json' \ -d '{ "user_id": "user-test-16d9ba61-97a1-4ba4-9720-b03761dc50c6", "domain": "example.com", "return_passkey_credential_options": true }' ``` -------------------------------- ### Before: Global Static Client Initialization Source: https://stytch.com/docs/api-reference/consumer/mobile-sdks/ios/upgrade-guide Demonstrates the older method of configuring and using a global static Stytch client. ```swift import StytchCore // Configure first (typically in AppDelegate or App.init) StytchClient.configure(configuration: .init(publicToken: "public-token-live-...")) // Then use the global static anywhere let response = try await StytchClient.otps.send(parameters: params) ``` -------------------------------- ### Get Synchronous Session - React SDK Source: https://stytch.com/docs/api-reference/consumer/frontend-sdks/react/methods/sessions/get-session-sync Use the `useStytch` hook to get the `stytch` instance and then call `session.getSync()` to retrieve the cached session object. This example displays the session ID if a session exists, otherwise it indicates no active session. ```javascript import { useStytch } from '@stytch/react'; export const SessionDisplay = () => { const stytch = useStytch(); const session = stytch.session.getSync(); return session ? (
Session ID: {session.session_id}
) : (No active session
); }; ``` -------------------------------- ### Install Stytch SDK Source: https://stytch.com/docs/consumer-auth/authentication/magic-links/adding-magic-links-to-custom-auth-flow Install the Stytch Node.js SDK using npm. This is the first step to using Stytch's backend authentication features. ```bash npm install stytch ``` -------------------------------- ### cryptoWallets.authenticateStart Source: https://stytch.com/docs/api-reference/consumer/frontend-sdks/vanilla-js/methods/crypto-wallets/authenticate-start Wraps the Crypto Wallet Authenticate Start endpoint. Call this method to prompt the user to sign a challenge using their crypto wallet. For Ethereum crypto wallets, the challenge will follow the Sign In With Ethereum (SIWE) protocol if you have toggled **SIWE Enabled** in the SDK Configuration page. The domain and URI will be inferred automatically, but you may optionally override the URI. Load the challenge data by calling `cryptoWallets.authenticateStart()`. You’ll then pass this challenge to the user’s wallet for signing. You can do so by using the crypto provider’s built-in API and by including the `crypto_wallet_address` and challenge that is provided from `cryptoWallets.authenticateStart()`. See Ethereum’s EIP-1193 for an example of Ethereum’s provider API. ```APIDOC ## cryptoWallets.authenticateStart ### Description Initiates the crypto wallet authentication process by requesting a challenge from Stytch, which the user will sign. ### Method `cryptoWallets.authenticateStart(params)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **crypto_wallet_type** (string) - Required - The type of wallet to authenticate. Currently `ethereum` and `solana` are supported. Wallets for any EVM-compatible chains (such as Polygon or BSC) are also supported and are grouped under the `ethereum` type. - **crypto_wallet_address** (string) - Required - The crypto wallet address to authenticate. - **siwe_params** (object) - Optional - The parameters for a Sign In With Ethereum (SIWE) message. May only be passed if the `crypto_wallet_type` is `ethereum` and if **SIWE Enabled** is toggled in the Frontend SDK page. - **uri** (string) - Optional - Defaults to `window.location.origin`. An RFC 3986 URI referring to the resource that is the subject of the signing. - **statement** (string) - Optional - A human-readable ASCII assertion that the user will sign. The statement may only include reserved, unreserved, or space characters according to RFC 3986 definitions, and must not contain other forms of whitespace such as newlines, tabs, and carriage returns. - **chain_id** (string) - Optional - The EIP-155 Chain ID to which the session is bound. Defaults to `1`. Must be the string representation of an integer between 1 and 9,223,372,036,854,775,771, inclusive. - **issued_at** (string) - Optional - The time when the message was generated. Defaults to the current time. All timestamps in our API conform to the RFC 3339 standard and are expressed in UTC, e.g. `2021-12-29T12:33:09Z`. - **not_before** (string) - Optional - The time when the signed authentication message will become valid. Defaults to the current time. All timestamps in our API conform to the RFC 3339 standard and are expressed in UTC, e.g. `2021-12-29T12:33:09Z`. - **message_request_id** (string) - Optional - A system-specific identifier that may be used to uniquely refer to the sign-in request. The `message_request_id` must be a valid pchar according to RFC 3986 definitions. - **resources** (array[string]) - Optional - A list of information or references to information the user wishes to have resolved as part of authentication. Every resource must be an RFC 3986 URI. ### Request Example ```javascript const { challenge } = await stytch.cryptoWallets.authenticateStart({ crypto_wallet_address: "0x1234567890abcdef1234567890abcdef12345678", crypto_wallet_type: "ethereum", siwe_params: { statement: "Please sign this message to confirm your identity.", uri: "https://example.com", chain_id: "1", issued_at: "2023-01-01T12:00:00Z", not_before: "2023-01-01T12:05:00Z", message_request_id: "my-unique-request-id", resources: ["https://example.com/resource1", "https://example.com/resource2"] } }); ``` ### Response #### Success Response (200) - **challenge** (string) - The challenge string that needs to be signed by the user's crypto wallet. - **request_id** (string) - The unique identifier for the request. #### Response Example ```json { "challenge": "Signing in with Project: 7_EPetPqfdEiDCJtgad6-xsXytN3Ee9tx6mdRTQK3fC7-J2PDxpP1GAvYB9Ic4E09h-K88STiRIzKSGP", "request_id": "request-id-test-b05c992f-ebdc-489d-a754-c7e70ba13141", "status_code": 200 } ``` ``` -------------------------------- ### Get Ethereum Address from MetaMask Source: https://stytch.com/docs/consumer-auth/authentication/crypto-wallets/api Fetches the user's MetaMask Ethereum address. Ensure `window.ethereum` is defined, indicating MetaMask is installed. ```javascript const [address] = await window.ethereum.request({ method: 'eth_requestAccounts' }); ``` -------------------------------- ### Initialize Stytch B2B SDK and Provider Source: https://stytch.com/docs/api-reference/consumer/mobile-sdks/react-native/quickstart Import necessary components, create a Stytch client configuration with your public token, and wrap your application with the StytchB2BProvider. ```javascript import { createStytchB2B, StytchClientConfiguration, StytchB2BProvider, useStytchB2B, useStytchMember, useStytchMemberSession, useStytchOrganization, useStytchB2BAuthenticationState, } from '@stytch/react-native-b2b'; import { B2BAuthenticationState } from '@stytch/react-native-b2b'; const stytch = createStytchB2B( new StytchClientConfiguration('public-token-live-...') ); function App() { return (