Getting started overview
Integrating Stytch involves setting up a developer account, obtaining API credentials, and making an initial API call to confirm connectivity. This process typically begins within the Stytch documentation, which provides comprehensive guides for various authentication methods. The initial setup focuses on obtaining the necessary API keys to authenticate requests from your application to Stytch's services. Stytch's platform is designed to abstract aspects of user authentication, including session management and token handling, which are foundational elements of modern identity systems as described by organizations like the OAuth 2.0 framework.
Before making your first API request, ensure you understand the basic flow:
- Sign up for a Stytch account.
- Create a new project within the Stytch Dashboard.
- Retrieve your project's
project_id,secret, andpublic_token. - Choose an authentication method (e.g., email magic links, OAuth, SMS OTP) for your first test.
- Send an authenticated request to a Stytch API endpoint.
This streamlined process allows developers to quickly implement and test authentication features without managing direct user credentials or complex cryptographic operations.
Create an account and get keys
To begin using Stytch, navigate to the Stytch homepage and select the option to sign up. The Developer Plan offers a free tier supporting up to 1,000 monthly active users (MAUs), which is suitable for initial development and testing. Once registered, you will be directed to the Stytch Dashboard.
Within the dashboard, a new project is automatically created for you. To access your API credentials:
- From the dashboard sidebar, select API Keys under your project.
- You will see three key components for your project:
- Project ID: A unique identifier for your project.
- Project Secret: A secret key used for server-side authentication. This should be kept confidential.
- Public Token: A public key used for client-side authentication, typically embedded in frontend applications.
It is crucial to treat the Project Secret as sensitive information and store it securely, never exposing it in client-side code. The Stytch API Keys documentation provides more detailed guidance on handling and rotating these credentials. For production environments, consider environment variables or secret management services for storing your Project Secret.
For testing, Stytch provides a sandbox environment. Requests made to the sandbox endpoints using your test API keys will not affect production data or incur charges. The distinct sets of keys for test and live environments prevent accidental data exposure or billing discrepancies during the development phase. Ensure you are using the correct set of keys (test vs. live) depending on your current development stage.
The dashboard also allows you to manage multiple projects, each with its own set of API keys, enabling segregated development and production environments or separate applications under a single Stytch account.
| Step | What to do | Where |
|---|---|---|
| 1. Account Creation | Sign up for a free Stytch Developer Plan. | Stytch Homepage |
| 2. Project Setup | A project is automatically created. Review its settings. | Stytch Dashboard |
| 3. Get API Keys | Locate your Project ID, Secret, and Public Token. | Stytch Dashboard > API Keys |
| 4. Choose SDK (Optional) | Select a client or server-side SDK for your language. | Stytch SDKs documentation |
| 5. Make First Request | Send an authenticated POST request to a Stytch endpoint. | See example below or Stytch API Reference |
Your first request
To make your first authenticated request, you'll use an API endpoint that initiates a passwordless flow, such as sending an email magic link. This example uses the Stytch Node.js SDK for clarity, but the principles apply across Stytch's supported SDKs (Python, Ruby, Go, Java, React, iOS, Android).
First, install the Node.js SDK:
npm install stytch
Next, create a file (e.g., send_magic_link.js) and add the following code. Replace YOUR_PROJECT_ID and YOUR_PROJECT_SECRET with your actual test credentials from the Stytch Dashboard.
const stytch = require('stytch');
const client = new stytch.Client({
project_id: process.env.STYTCH_PROJECT_ID || 'YOUR_PROJECT_ID',
secret: process.env.STYTCH_SECRET || 'YOUR_PROJECT_SECRET',
env: stytch.Client.envs.test, // Use stytch.Client.envs.live for production
});
async function sendMagicLink() {
try {
const response = await client.magicLinks.email.send({
email: '[email protected]',
login_magic_link_url: 'http://localhost:3000/authenticate',
signup_magic_link_url: 'http://localhost:3000/authenticate',
});
console.log('Magic link sent successfully:', response);
} catch (error) {
console.error('Error sending magic link:', error.error_message);
}
}
sendMagicLink();
Ensure you set the STYTCH_PROJECT_ID and STYTCH_SECRET environment variables or replace the placeholders directly. The env: stytch.Client.envs.test setting ensures requests go to the Stytch test environment, preventing accidental interactions with live data. The login_magic_link_url and signup_magic_link_url specify where the user will be redirected after clicking the magic link. For this example, http://localhost:3000/authenticate is a placeholder representing your application's authentication endpoint. After executing this script, Stytch will send an email containing a magic link to [email protected]. Check the email inbox for a link that, when clicked, would typically verify the user and issue a session token via your application's redirect endpoint.
This request demonstrates:
- Initialization of the Stytch client with API keys.
- Targeting a specific authentication method (email magic links).
- Handling potential success or error responses.
The response object contains details about the sent magic link and a request_id, which can be useful for debugging and logging purposes. The Stytch API reference for email magic links provides full details on this endpoint's parameters and expected responses.
Common next steps
After successfully sending your first request, several common next steps can further your Stytch integration:
-
Handle Magic Link Redirect: Implement the endpoint (e.g.,
/authenticate) specified inlogin_magic_link_url. This endpoint receives the magic link token in the URL query parameters. Your application will then call the Stytch Authenticate Magic Link endpoint to exchange this token for a session token and user data.// Example Express.js handler for /authenticate app.get('/authenticate', async (req, res) => { const token = req.query.token; try { const authResponse = await client.magicLinks.authenticate({ token: token, }); // Store authResponse.session_token and authResponse.user for your application res.status(200).send('Authentication successful!'); } catch (error) { res.status(400).send('Authentication failed: ' + error.error_message); } }); -
Explore Other Authentication Methods: Stytch supports various authentication factors beyond magic links, including SMS OTP, WhatsApp OTP, OAuth, TOTP, and WebAuthn/FIDO2. Investigate the Stytch API documentation for integrating these methods based on your application's requirements for consumer or B2B authentication.
For example, to implement FIDO2 WebAuthn, you would use Stytch's WebAuthn registration and authentication endpoints, requiring both client-side JavaScript for interacting with the browser's WebAuthn API and server-side calls to Stytch for credential management. - Integrate with Your Frontend: Use one of Stytch's client-side SDKs (e.g., React, iOS, Android) or Stytch UI components to build seamless login and signup experiences. These SDKs simplify the process of gathering user input and securely passing it to your backend, which then interacts with the Stytch API.
- Implement Session Management: After authenticating a user, Stytch returns a session token. Your application should store this token securely (e.g., in an HTTP-only cookie) and use it for subsequent authenticated requests to your backend. Stytch provides session authentication endpoints that allow your backend to validate the session token and retrieve user details for each request.
- Error Handling and Logging: Implement robust error handling for all Stytch API calls. Stytch returns detailed error messages and codes, which can assist in debugging and providing user-friendly feedback. Integrate logging to monitor authentication flows and identify issues promptly.
-
Move to Production Environment: Once development and testing are complete, switch your API keys to the live project keys and update your client environment variable to
stytch.Client.envs.live. Review Stytch pricing details to understand costs associated with live usage beyond the free tier.
Troubleshooting the first call
Encountering issues during your first API call is common. Here's a guide to diagnosing and resolving typical problems:
-
Invalid API Keys: Double-check that your
project_idandsecretexactly match the test keys in your Stytch Dashboard. Ensure there are no leading or trailing spaces. Remember that test keys begin withproject-test-, and live keys withproject-live-. Using live keys with the test environment, or vice-versa, will result in authentication failures.Error: Unauthorized (401) Message: Invalid Project ID or Secret. -
Incorrect Environment: Verify that the
envparameter in your Stytch client initialization matches the type of API keys you are using (stytch.Client.envs.testfor test keys,stytch.Client.envs.livefor live keys). Mismatched environments will also lead to authentication failures.Error: Request to production environment with test keys. -
Network Connectivity: Confirm that your application has outbound network access to Stytch's API endpoints. Firewall rules or proxy settings can sometimes block these connections. Test by pinging a public API endpoint or using a simple
curlcommand from your environment. -
Missing Parameters: Review the API reference for the specific endpoint you are calling (Email Magic Links Send in our example). Ensure all required parameters are present and correctly formatted. For instance, an invalid email format for the
emailparameter will result in a validation error.Error: Bad Request (400) Message: Invalid email address format. - SDK Version Compatibility: Ensure you are using a recent and compatible version of the Stytch SDK. Outdated SDKs might not support new API features or might contain bugs. Refer to the Stytch SDK documentation for recommended versions.
-
Checking Stytch Dashboard Logs: The Stytch Dashboard provides detailed logs for all API requests made to your project, including successful calls and errors. This is invaluable for pinpointing exactly where a request failed and viewing the specific error message returned by Stytch. Navigate to Logs in your project sidebar to review these.
The log entries include the timestamp, endpoint, status code, request body, and response body, allowing for a comprehensive audit of your API interactions. This can help distinguish between client-side errors (e.g., incorrect parameters) and server-side issues (e.g., Stytch processing errors).