Setting up Email Magic Links with the Stytch API
Managing user login with Stytch enables you to authenticate users on an ongoing basis via one-click, passwordless login. When a user signs up for your app, you'll add them to Stytch. Then, whenever a user goes to login to your app, authenticate them via a magic link. Check out the Stytch and Feathery integration guide to get started.
Step 1: Build a sign up or login view
If you don't already have one, you'll need to build a sign up or login view for your app. You can collect any information you want, but you'll need to include an email field so the user can login with their email later.
Step 2: Create a route for authentication
Create a route that will act as your magic link endpoint. Users will be directed there from the login email. The route should accept a token as a query parameter that you will use to authenticate. For example, your route should be something like https://example.com/authenticate. Users will be directed to https://example.com/authenticate?token=abc, where abc is the token you'll pass to our authentication endpoint.
Step 3: Add redirect URLs to the Stytch dashboard
Add the login and signup URLs to the project's list of predefined redirect URLs in the dashboard. For more information on why this step is necessary, please check out the documentation here.
By default, all redirect URLs are set to http://localhost:3000 for the Test environment.
Step 4: Send a magic link to log in or create a Stytch user
Send either a login or create magic link to the user based on if the email is associated with a user already. If the user was created, use the user_id returned in the response to manage that user within Stytch. Save this user_id with your user's record in your app's storage.
curl --request POST \\
--url https://test.stytch.com/v1/magic_links/email/login_or_create \\
-u 'PROJECT_ID:SECRET' \\
-H 'Content-Type: application/json' \\
-d '{
"email": "sandbox@stytch.com",
"login_magic_link_url": "https://example.com/authenticate",
"signup_magic_link_url": "https://example.com/authenticate"
}
Step 5: Logging in a user: authenticating a token
Once the user clicks the magic link from the email and is directed to either the login_magic_link_url or signup_magic_link_url, you'll use the token from the url to call the authenticate endpoint to log the user in. You'll need to manage the user session from your app.
Make sure to replace the token in the url with the actual token.
curl --request POST \\
--url https://test.stytch.com/v1/magic_links/authenticate \\
-u 'PROJECT_ID:SECRET' \\
-H 'Content-Type: application/json' \\
-d '{
"token": "SeiGwdj5lKkrEVgcEY3QNJXt6srxS3IK2Nwkar6mXD4="
}'
Step 6: Going live
Request your Live API keys in the dashboard and store them somewhere safe. We suggest using environment variables for your projectID and secret to keep them secure. Then, update the URL you’re using from https://test.stytch.com to https://api.stytch.com