<@U04UQ68083H> How do I trigger a Magic Link login...
# ory-copilot
c
@chilly-king-10285 How do I trigger a Magic Link login using the API?
b
A message from kapa.ai
To trigger a Magic Link login using the API in Ory Kratos (Ory Identities), you need to use the verification or recovery flow with the method set to link. Here’s how you can do it: 1. Initiate the Verification or Recovery Flow Start the flow by making a request to the appropriate endpoint (e.g.,
/self-service/verification/api
or
/self-service/recovery/api
). 2. Submit the Email and Method In the request body, set the
method
to
link
and provide the user's email. For example, using the verification flow:
Copy code
json    {      "method": "link",      "email": "<mailto:user@example.com|user@example.com>"    }
This will trigger Ory to send a magic link to the provided email address. The user can then click the link to complete the login or verification process. The same approach applies to the recovery flow if you want to use a magic link for account recovery. 3. API Reference The API expects the following fields in the request body: - `method`: Must be set to
link
for magic link. - `email`: The email address to send the magic link to. Example (for verification):
Copy code
json    {      "method": "link",      "email": "<mailto:user@example.com|user@example.com>"    }
Example (for recovery):
Copy code
json    {      "method": "link",      "email": "<mailto:user@example.com|user@example.com>"    }
For more details, see the [Ory API Reference for updateVerificationFlow](https://www.ory.sh/docs/reference/api) and the [account recovery documentation](https://www.ory.sh/docs/identities/get-started/account-recovery). Note: Ory considers the "magic link" method a legacy solution and recommends using the "one-time code" (
code
) method instead, as magic links may be deprecated in future releases. If you use magic links, ensure your UI and flows are compatible and be aware of the potential drawbacks (e.g., email scanners invalidating links, issues on mobile devices) [Choosing the right strategy](https://www.ory.sh/docs/kratos/self-service/flows/verify-email-account-activation#choosing-the-right-strategy). If you are using Ory Polis Admin Portal, magic link authentication is handled via NextAuth and is configured through environment variables, not directly via the Ory API [Get started with Admin Portal](https://www.ory.sh/docs/polis/admin-portal). If you need a code example for the Admin API to create a recovery link (for administrative purposes), see [Administrative account recovery](https://www.ory.sh/docs/kratos/manage-identities/account-recovery#magic-links). If you need more specific code samples or details for your use case, please clarify which Ory product and flow you are targeting.
c
SHow how to trigger a OTC login via the API
@chilly-king-10285 Show how to trigger an OTC login using the API
b
A message from kapa.ai
To trigger a one-time code (OTC) login (passwordless login via code) using the Ory API, you need to use the login flow with the
code
method enabled. Here’s how you can do it: 1. Enable the one-time code strategy for passwordless login Make sure your configuration has passwordless OTC enabled:
Copy code
yaml    selfservice:      methods:        code:          passwordless_enabled: true
Or via CLI:
Copy code
ory patch identity-config <your-project-id> \    --add '/selfservice/methods/code/passwordless_enabled=true'
[Email and SMS one-time-code authentication](https://www.ory.sh/docs/kratos/passwordless/one-time-code) 2. Start the login flow Initiate a login flow by making a request to the login endpoint (e.g.,
/self-service/login/api
). 3. Submit the identifier (email or phone) to request the code In the first step, submit the user's identifier (email or phone) and set the method to
code
. Example request body:
Copy code
json    {      "method": "code",      "identifier": "<mailto:user@example.com|user@example.com>"    }
This will send a one-time code to the user’s email or phone. 4. Submit the code to complete login Once the user receives the code, submit it along with the method to the same flow:
Copy code
json    {      "method": "code",      "code": "123456"    }
[Ory API Reference – updateLoginFlow](https://www.ory.sh/docs/reference/api) Summary of the flow: - Start login flow → submit identifier with
method: code
→ user receives code → submit code with
method: code
to complete login. Note: Make sure your identity schema marks the correct trait (email or phone) as the identifier for the
code
method. See [Passwordless one-time code login identifier](https://www.ory.sh/docs/kratos/manage-identities/customize-identity-schema#passwordless-one-time-code-login-identifier). If you need to resend the code, you can include the
resend
field in your request as per the API reference. --- References integrated above from: - [Email and SMS one-time-code authentication](https://www.ory.sh/docs/kratos/passwordless/one-time-code) - [Ory API Reference – updateLoginFlow](https://www.ory.sh/docs/reference/api) - [Passwordless one-time code login identifier](https://www.ory.sh/docs/kratos/manage-identities/customize-identity-schema#passwordless-one-time-code-login-identifier)
c
@chilly-king-10285 Show how to use the createIdentityRaw method of the IndentityAPI to create a new idenity and get the identity in the response.
b
A message from kapa.ai
I'm sorry, but the knowledge sources provided do not contain information or code examples specifically for the use of the
createIdentityRaw
method of the IdentityAPI. The available documentation and SDK examples only reference the standard
CreateIdentity
method, both in Go and via HTTP API, but do not mention or demonstrate a
createIdentityRaw
method. If you need to create an identity and get the identity in the response, you can use the standard
CreateIdentity
method as shown in the Go SDK examples:
Copy code
go createdIdentity, r, err := apiClient.IdentityApi.CreateIdentity(context.Background()).CreateIdentityBody(CreateIdentityBody).Execute() if err != nil {  fmt.Fprintf(os.Stderr, "Error when calling `FrontendApi.CreateIdentity``: %v\n", err)  fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) } // response from `CreateIdentity`: Identity fmt.Fprintf(os.Stdout, "Created identity with ID: %v\n", createdIdentity.Id)
[Use Identity Management API (Go)](https://www.ory.sh/docs/kratos/self-hosted/go#use-identity-management-api) If you are looking for information specifically about
createIdentityRaw
, the knowledge sources do not contain enough information to answer your question.
c
@chilly-king-10285 Show how to trigger an OTC login using the typescript API. Show example code.
b
A message from kapa.ai
To trigger a one-time code (OTC) login using the TypeScript API with Ory, you can use the
@ory/client
package. The process involves creating a login flow and then submitting the user's identifier (such as email) with the
code
method. Below is an example based on the available documentation:
Copy code
typescript import { Configuration, FrontendApi } from "@ory/client"  const ory = new FrontendApi(   new Configuration({     basePath: "<https://your-ory-project-url>", // Replace with your Ory project URL     baseOptions: {       withCredentials: true,     },   }) )  async function otcLogin(identifier: string) {   // 1. Create a login flow   const { data: flow } = await ory.createBrowserLoginFlow()    // 2. Submit the identifier to request the one-time code   await ory.updateLoginFlow({     flow: flow.id,     updateLoginFlowBody: {       method: "code",       identifier, // e.g., "<mailto:user@example.com|user@example.com>"     },   })    // At this point, the user will receive a one-time code via email or SMS.   // You would then prompt the user to enter the code and submit it as follows:    // Example: After user enters the code   // await ory.updateLoginFlow({   //   flow: flow.id,   //   updateLoginFlowBody: {   //     method: "code",   //     code: "123456", // The code the user received   //   },   // }) }
This code demonstrates how to: 1. Start a login flow. 2. Submit the identifier with the
code
method to trigger sending the OTC. 3. (Commented) Submit the received code to complete the login. Make sure your Ory project is configured to enable the one-time code method for passwordless login, and your identity schema is set up correctly for the identifier ([see docs](https://www.ory.sh/docs/kratos/passwordless/one-time-code)). > The knowledge sources provide TypeScript examples for similar flows and confirm the use of
@ory/client
for interacting with Ory APIs, but do not show a full OTC login example. The above code is directly derived from the documented flow and TypeScript usage patterns in the official docs [Passwordless authentication](https://www.ory.sh/docs/kratos/bring-your-own-ui/custom-ui-advanced-integration#passwordless-authentication) and [Email and SMS one-time-code authentication](https://www.ory.sh/docs/kratos/passwordless/one-time-code).
c
@chilly-king-10285 Use the TypeScript client-fetch sdk and show how to trigger an OTC login via the API. Show code examples.
b
A message from kapa.ai
To trigger a one-time code (OTC) login using the TypeScript
@ory/client-fetch
SDK, you need to: 1. Create a login flow using the API. 2. Submit the identifier (such as email) with the
code
method to request the OTC. Below is a code example based on the official documentation for using the
@ory/client-fetch
SDK in a React app. The same approach applies for any TypeScript environment:
Copy code
typescript import { FrontendApi, Configuration } from "@ory/client-fetch"  const basePath = "<https://your-ory-project-url>" // Replace with your Ory project URL  // Initialize Ory client const ory = new FrontendApi(   new Configuration({     basePath,     credentials: "include",   }), )  async function otcLogin(identifier: string) {   // 1. Create a login flow   const flow = await ory.createBrowserLoginFlow()    // 2. Submit the identifier to request the one-time code   await ory.updateLoginFlow({     flow: flow.data.id,     updateLoginFlowBody: {       method: "code",       identifier, // e.g., "<mailto:user@example.com|user@example.com>"     },   })    // The user will now receive a one-time code via email or SMS.   // You would then prompt the user to enter the code and submit it as follows:    // Example: After user enters the code   // await ory.updateLoginFlow({   //   flow: flow.data.id,   //   updateLoginFlowBody: {   //     method: "code",   //     code: "123456", // The code the user received   //   },   // }) }
This code follows the documented pattern for making authenticated calls and interacting with Ory flows using the
@ory/client-fetch
SDK. The key steps are to create the login flow and then update it with the
code
method and the user's identifier. After the user receives the code, you update the flow again with the code to complete the login process. For more details on making authenticated calls and using the SDK, see the [official Ory documentation for integrating authentication into React + API](https://www.ory.sh/docs/getting-started/integrate-auth/react#make-authenticated-calls-to-your-api). > Note: The knowledge sources do not provide a full, explicit OTC login example with
@ory/client-fetch
, but the above code is directly derived from the documented usage patterns and the official SDK initialization and flow update examples [Make authenticated calls to your API](https://www.ory.sh/docs/getting-started/integrate-auth/react#make-authenticated-calls-to-your-api).
c
@chilly-king-10285 Then how do I get a valid session token after submitting the OTC to the ory.updateLoginFlow method?
b
A message from kapa.ai
After you submit the one-time code (OTC) to the
ory.updateLoginFlow
method, a successful response from the Ory API will include the session token in the JSON payload if you are using the API flow (not the browser flow). Specifically, for API clients, the response contains both the
session_token
and the
session
object. You can extract the session token from the response like this:
Copy code
json {   "session_token": "oFZzgLpsacUpUy2cvQPtrGa2046WcXCR",   "session": {     // session details   } }
This is confirmed in the documentation for API clients, which states: > For API Clients, Ory Identities responds with a JSON payload which includes the identity which just authenticated, the session, and the Ory Session Token [Docs > Kratos > Self-service > Flows > Login > Successful login](https://www.ory.sh/docs/kratos/self-service/flows/user-login#api-clients). So, after calling
ory.updateLoginFlow
with the OTC, you can access the session token from the response:
Copy code
typescript const response = await ory.updateLoginFlow({   flow: flowId,   updateLoginFlowBody: {     method: "code",     code: "123456", // The code the user received   }, })  // The session token is available in the response for API flows const sessionToken = response.data.session_token
Note: - If you are using a browser flow, the session is established via a cookie, and you will not receive a session token in the response. The session token is only returned for API flows (e.g., mobile or native apps) [Docs > Kratos > Self-service > Flows > Login > Successful login](https://www.ory.sh/docs/kratos/self-service/flows/user-login#api-clients). - For browser flows, authentication is managed via cookies set by the server. If you need to check the session, you can use the
/sessions/whoami
endpoint with the session token in the
Authorization: Bearer
header for API flows, or with the session cookie for browser flows [Docs > Identities > Sign-in > Check session status](https://www.ory.sh/docs/identities/sign-in/check-session-token-cookie-api).
c
@chilly-king-10285 Type error: Property ‘data’ does not exist on type ‘LoginFlow’. 61 | try { 62 | const otc_login_result = await oryFrontendAPI.updateLoginFlow({
63 | flow: flow.data.id,
| ^ 64 | updateLoginFlowBody: { 65 | method: “code”, 66 | identifier: identifier
b
A message from kapa.ai
Thank you for pointing out the error. According to the knowledge sources, the
updateLoginFlow
method from the Ory TypeScript SDK returns the updated login flow object directly, not an object with a
.data
property. Therefore, you should use
flow.id
instead of
flow.data.id
when calling
updateLoginFlow
. Here’s how you should structure your code:
Copy code
typescript // Assume 'flow' is the LoginFlow object returned from createBrowserLoginFlow or getLoginFlow const otc_login_result = await oryFrontendAPI.updateLoginFlow({   flow: flow.id, // not flow.data.id   updateLoginFlowBody: {     method: "code",     identifier: identifier,   }, })
This matches the usage shown in the official Ory documentation and code samples, where the flow object itself contains the
id
property, not a nested
data
object [Docs > Kratos > Bring-your-own-ui > Integration basics > Login flow](https://www.ory.sh/docs/kratos/bring-your-own-ui/custom-ui-basic-integration#get-login-flow). If you are using the
@ory/client-fetch
or
@ory/client
SDK, always refer to the returned object's structure as shown in the documentation and examples. If you get the flow from
createBrowserLoginFlow
or
getLoginFlow
, use
flow.id
directly. If you need to access the session token after a successful OTC login, please note that the knowledge sources do not provide a TypeScript code example for extracting the session token, but for API flows, the session token is returned in the response as described in the documentation [Docs > Kratos > Self-service > Flows > Login > Successful login](https://www.ory.sh/docs/kratos/self-service/flows/user-login#api-clients). For browser flows, authentication is managed via cookies. If you need further clarification or a more specific example, please provide more context about your flow type (API or browser).
c
@chilly-king-10285 Type error: Type ‘{ method: “code”; identifier: string; }’ is not assignable to type ‘UpdateLoginFlowBody’. Type ‘{ method: “code”; identifier: string; }’ is not assignable to type ‘{ method: “code”; } & UpdateLoginFlowWithCodeMethod’. Property ‘csrf_token’ is missing in type ‘{ method: “code”; identifier: string; }’ but required in type ‘UpdateLoginFlowWithCodeMethod’. 62 | const otc_login_result = await oryFrontendAPI.updateLoginFlow({ 63 | flow: flow.id,
64 | updateLoginFlowBody: {
| ^ 65 | method: “code”, 66 | identifier: identifier
b
A message from kapa.ai
The error you are seeing is because the
csrf_token
field is required when using the
code
method in the
updateLoginFlow
API call. According to the Ory API reference, when updating the login flow with the code method, the request body must include the
csrf_token
field along with
method
and, if applicable,
identifier
or
code
fields. The
csrf_token
is typically provided as part of the login flow object you receive when you initiate or fetch the login flow. Here’s how you should structure your request:
Copy code
typescript const otc_login_result = await oryFrontendAPI.updateLoginFlow({   flow: flow.id,   updateLoginFlowBody: {     method: "code",     identifier: identifier,     csrf_token: flow.ui.nodes.find((node) => node.attributes.name === "csrf_token")?.attributes.value,   }, })
-
csrf_token
is required for browser login flows and must be extracted from the flow object, typically from
flow.ui.nodes
. -
method
should be set to
"code"
. -
identifier
is the user's email or phone number. This requirement is explicitly stated in the API reference: > "Sending the anti-csrf token is only required for browser login flows." [Ory API Reference – updateLoginFlow](https://www.ory.sh/docs/reference/api) If you are using an API flow (not browser), the CSRF token may not be required, but for browser flows, it is mandatory. If you need to submit the code after the user receives it, the body should look like this:
Copy code
typescript const otc_login_result = await oryFrontendAPI.updateLoginFlow({   flow: flow.id,   updateLoginFlowBody: {     method: "code",     code: userInputCode,     csrf_token: flow.ui.nodes.find((node) => node.attributes.name === "csrf_token")?.attributes.value,   }, })
If you need more details on how to extract the CSRF token from the flow object, please refer to the structure of the flow as returned by the Ory API. If you have further questions or need clarification, please provide more context about your flow and how you are obtaining the login flow object.
c
@chilly-king-10285 Type error: Property ‘name’ does not exist on type ‘UiNodeAttributes’. Property ‘name’ does not exist on type ‘{ node_type: “a”; } & UiNodeAnchorAttributes’. 65 | method: “code”, 66 | identifier: identifier,
67 | csrf_token: flow.ui.nodes.find((node) => node.attributes.name === “csrf_token”)?.attributes.value,
| ^ 68 | }, 69 | })
b
A message from kapa.ai
You're encountering this error because not all
UiNode
types in Ory have a
name
property on their
attributes
. Only certain node types, such as input nodes, have the
name
attribute. To safely access the
name
property, you should first check that the node's attributes are of the input type. The Ory SDK provides a helper function
isUiNodeInputAttributes
from
@ory/integrations/ui
to help with this. Here’s how you can use it, as shown in the official documentation:
Copy code
typescript import { isUiNodeInputAttributes } from "@ory/integrations/ui"  // ...  const csrfToken = flow.ui.nodes.find(   (node) =>     isUiNodeInputAttributes(node.attributes) &&     node.attributes.name === "csrf_token" )?.attributes.value
This approach ensures you only try to access the
name
property on nodes where it exists, avoiding the type error you encountered. This pattern is directly shown in the Ory documentation for mapping CSRF tokens in React and TypeScript apps [Docs > Kratos > Bring-your-own-ui > Integration basics > Debug > Cross-site request forgery errors](https://www.ory.sh/docs/kratos/bring-your-own-ui/custom-ui-basic-integration#debug). Summary: - Use
isUiNodeInputAttributes
to check the node type before accessing
name
. - This avoids the type error and is the recommended approach in the Ory docs. If you need a full example, let me know!
c
@chilly-king-10285 THere’s no npm package called
@​ory/integrations/ui
b
A message from kapa.ai
You're correct—according to the knowledge sources, the code examples reference
@ory/integrations/ui
for helpers like
isUiNodeInputAttributes
, but there is no explicit mention in the documentation about installing or using an npm package called
@ory/integrations/ui
. The documentation simply uses these helpers in the code examples without further explanation about their origin or installation. If you are following the official Ory documentation and cannot find the
@ory/integrations/ui
package, you may need to manually check the structure of the node attributes to safely access the
name
property. For example, you can use a type guard to ensure the attribute exists:
Copy code
typescript const csrfToken = flow.ui.nodes.find(   (node) =>     (node.attributes as any).name === "csrf_token" )?.attributes.value
This approach is not as type-safe as using a helper, but it matches the structure shown in the knowledge sources, where the CSRF token is extracted from the
flow.ui.nodes
array by looking for a node with
attributes.name === "csrf_token"
 [Debug: Cross-site request forgery errors](https://www.ory.sh/docs/kratos/bring-your-own-ui/custom-ui-basic-integration#debug). If you need a more robust solution, you may need to implement your own type guard based on the structure of
UiNode
and
UiNodeInputAttributes
as described in the Ory documentation. In summary: - The knowledge sources reference
@ory/integrations/ui
but do not provide installation instructions or confirm its availability as an npm package. - If the package is not available, use a manual type check as shown above. - The official documentation does not clarify this point further.
c
@chilly-king-10285 Type error: Property ‘value’ does not exist on type ‘UiNodeAttributes’. Property ‘value’ does not exist on type ‘{ node_type: “a”; } & UiNodeAnchorAttributes’. 61 | (node) => 62 | (node.attributes as any).name === “csrf_token”
63 | )?.attributes.value
b
A message from kapa.ai
You're encountering this TypeScript error because not all
UiNodeAttributes
have a
value
property—only certain node types (like input nodes) do. The Ory documentation shows that the CSRF token is found in a node of type
input
with the name
csrf_token
, and its value is under
attributes.value
for that node type. However, the docs do not provide a type-safe, canonical way to extract this in TypeScript without the
@ory/integrations/ui
helpers. What the docs show: The CSRF token node looks like this:
Copy code
json {   "type": "input",   "group": "default",   "attributes": {     "name": "csrf_token",     "type": "hidden",     "value": "By8X7TPnn/NMtXeDpK6sbshISK3t1WnezAtlMnFA6ZPsxxNmRsG8ks7WpsHMQtTLbxtqKJOiu4aArJok6/GOSw==",     "required": true,     "disabled": false,     "node_type": "input"   },   "messages": [],   "meta": {} }
[Understanding UI nodes and error messages](https://www.ory.sh/docs/kratos/concepts/ui-user-interface#hidden-input-node) How to extract the CSRF token (with type assertion): Since the knowledge sources do not provide a type-safe utility and only show direct property access, you can use a type assertion for this specific case:
Copy code
typescript const csrfNode = flow.ui.nodes.find(   (node) =>     (node.attributes as any).name === "csrf_token" ) const csrfToken = csrfNode ? (csrfNode.attributes as any).value : undefined
Caveat: This approach uses
as any
because the knowledge sources do not provide a more type-safe solution or a utility function for this purpose. If you want to avoid the error, you must ensure you only access
.value
on nodes where it exists, as shown above. Summary: - The error occurs because not all node types have a
value
property. - The documentation shows direct access to
attributes.value
for input nodes, but does not provide a type-safe helper. - Using a type assertion (
as any
) is the only approach shown or implied in the knowledge sources. If you need a more type-safe solution, the knowledge sources do not provide enough information to answer that.
c
@chilly-king-10285 ERROR: The request failed and the interceptors did not return an alternative response err: { “type”: “FetchError”, “message”: “The request failed and the interceptors did not return an alternative response: fetch failed: redirect count exceeded”, “stack”: FetchError: The request failed and the interceptors did not return an alternative response at FrontendApi.eval (webpack-internal:///(rsc)/./node_modules/@ory/client-fetch/dist/esm/runtime.js12131) at Generator.throw (<anonymous>) at rejected (webpack-internal:///(rsc)/./node_modules/@ory/client-fetch/dist/esm/runtime.js3765) at process.processTicksAndRejections (nodeinternal/process/task queues95:5) caused by: TypeError: fetch failed at nodeinternal/deps/undici/undici12442:11 at process.processTicksAndRejections (nodeinternal/process/task queues95:5) caused by: Error: redirect count exceeded at makeNetworkError (nodeinternal/deps/undici/undici5675:35) at httpRedirectFetch (nodeinternal/deps/undici/undici10696:32) at httpFetch (nodeinternal/deps/undici/undici10668:28) at process.processTicksAndRejections (nodeinternal/process/task queues95:5) at async nodeinternal/deps/undici/undici10440:20 at async mainFetch (nodeinternal/deps/undici/undici10430:20) at async httpFetch (nodeinternal/deps/undici/undici10668:22) at async nodeinternal/deps/undici/undici10440:20 at async mainFetch (nodeinternal/deps/undici/undici10430:20) at async httpFetch (nodeinternal/deps/undici/undici10668:22) at async nodeinternal/deps/undici/undici10440:20 at async mainFetch (nodeinternal/deps/undici/undici10430:20) at async httpFetch (nodeinternal/deps/undici/undici10668:22) at async nodeinternal/deps/undici/undici10440:20 at async mainFetch (nodeinternal/deps/undici/undici10430:20) at async httpFetch (nodeinternal/deps/undici/undici10668:22) at async nodeinternal/deps/undici/undici10440:20 at async mainFetch (nodeinternal/deps/undici/undici10430:20) at async httpFetch (nodeinternal/deps/undici/undici10668:22) at async nodeinternal/deps/undici/undici10440:20 at async mainFetch (nodeinternal/deps/undici/undici10430:20) at async httpFetch (nodeinternal/deps/undici/undici10668:22) at async nodeinternal/deps/undici/undici10440:20 at async mainFetch (nodeinternal/deps/undici/undici10430:20) at async httpFetch (nodeinternal/deps/undici/undici10668:22) at async nodeinternal/deps/undici/undici10440:20 at async mainFetch (nodeinternal/deps/undici/undici10430:20) at async httpFetch (nodeinternal/deps/undici/undici10668:22) at async nodeinternal/deps/undici/undici10440:20 at async mainFetch (nodeinternal/deps/undici/undici10430:20) at async httpFetch (nodeinternal/deps/undici/undici10668:22) at async nodeinternal/deps/undici/undici10440:20 at async mainFetch (nodeinternal/deps/undici/undici10430:20) at async httpFetch (nodeinternal/deps/undici/undici10668:22) at async nodeinternal/deps/undici/undici10440:20 at async mainFetch (nodeinternal/deps/undici/undici10430:20) at async httpFetch (nodeinternal/deps/undici/undici10668:22) at async nodeinternal/deps/undici/undici10440:20 at async mainFetch (nodeinternal/deps/undici/undici10430:20) at async httpFetch (nodeinternal/deps/undici/undici10668:22) at async nodeinternal/deps/undici/undici10440:20 at async mainFetch (nodeinternal/deps/undici/undici10430:20) at async httpFetch (nodeinternal/deps/undici/undici10668:22) at async nodeinternal/deps/undici/undici10440:20 at async mainFetch (nodeinternal/deps/undici/undici10430:20) at async httpFetch (nodeinternal/deps/undici/undici10668:22) at async nodeinternal/deps/undici/undici10440:20 at async mainFetch (nodeinternal/deps/undici/undici10430:20) at async httpFetch (nodeinternal/deps/undici/undici10668:22) at async nodeinternal/deps/undici/undici10440:20 “name”: “FetchError” }
b
A message from kapa.ai
The error message you are seeing—`FetchError: The request failed and the interceptors did not return an alternative response: fetch failed: redirect count exceeded`—indicates that the HTTP client (in this case, the
undici
library used by
@ory/client-fetch
) encountered too many HTTP redirects when trying to reach the Ory endpoint. Possible causes based on Ory documentation and known patterns: 1. Using the wrong flow type (browser vs. API): If you are using the browser flow endpoints (e.g.,
createBrowserLoginFlow
) from a server-side or API client context, Ory will respond with HTTP redirects intended for browsers. API clients (like Node.js or server-side code) do not handle these redirects as browsers do, which can result in a redirect loop and eventually the "redirect count exceeded" error. The Ory documentation states that browser flows are for browser-based clients, while API flows (e.g.,
createNativeLoginFlow
or
/self-service/login/api
) are for server-side or mobile clients. [Browser redirects and flow completion](https://www.ory.sh/docs/concepts/redirects#redirect-flows) 2. Incorrect base URL or misconfigured endpoints: If your Ory base URL is set to a domain that itself redirects (for example, from HTTP to HTTPS, or from a root domain to a subdomain), this can also cause redirect loops. 3. Custom domains and allow-list issues: If you are using a custom domain or have not properly configured allowed return URLs, Ory may redirect requests to error pages or default UIs, which can also result in redirect loops. [Browser redirects and flow completion - Troubleshooting](https://www.ory.sh/docs/concepts/redirects#troubleshooting) What you should do: - For server-side or API clients: Use the API flow endpoints (e.g.,
/self-service/login/api
) instead of browser flow endpoints. - Check your base URL: Ensure the
basePath
you provide to the Ory SDK is the correct API endpoint and does not itself redirect. - Check your flow creation: If you are running in a Node.js environment, use the API flow, not the browser flow. Example (API flow):
Copy code
typescript const flow = await ory.createNativeLoginFlow()
Instead of:
Copy code
typescript const flow = await ory.createBrowserLoginFlow()
Summary: The "redirect count exceeded" error is most commonly caused by using browser flow endpoints from a non-browser context, or by misconfigured URLs that cause redirect loops. The knowledge sources do not provide a more specific troubleshooting guide for this exact error, but the above points are directly supported by the Ory documentation on flow types and redirect handling. If you need more detailed troubleshooting, please provide information about your environment (browser, Node.js, etc.) and which Ory endpoints you are calling. [Browser redirects and flow completion](https://www.ory.sh/docs/concepts/redirects#redirect-flows) [Browser redirects and flow completion - Troubleshooting](https://www.ory.sh/docs/concepts/redirects#troubleshooting)
c
@chilly-king-10285 Error [ResponseError]: Response returned an error code at Generator.next (<anonymous>) { response: [Response] }
b
A message from kapa.ai
The error
Error [ResponseError]: Response returned an error code
indicates that the Ory API responded with an error status code (such as 400, 401, 403, etc.) rather than a successful response. This is a generic error that can occur for various reasons, such as invalid input, missing required fields, authentication issues, or CSRF protection failures. To troubleshoot this error: 1. Check the Error Response Body: Ory APIs return a standard JSON error format that includes details such as
error
,
error_description
,
message
, and
status_code
. Inspect the error response body to get more information about what went wrong. For example:
Copy code
json    {      "error": {        "status_code": 400,        "error": "The requested resource could not be found",        "error_description": "Object with ID 12345 does not exist",        "message": "The request was malformed or contained invalid parameters"      }    }
This structure is described in the Ory API reference for error responses [Ory API Reference](https://www.ory.sh/docs/reference/api). 2. Common Causes: - Missing or invalid parameters: Ensure all required fields are present and valid. - CSRF issues: If you are using browser flows, make sure to include the correct CSRF token in your request. Missing or invalid CSRF tokens are a common cause of 400/401 errors [CSRF troubleshooting](https://www.ory.sh/docs/troubleshooting/csrf). - Authentication/authorization issues: If you receive 401 or 403 errors, check your authentication credentials or session. 3. How to Debug: - Log or print the full error response from the API to see the detailed error message. - Review the Ory troubleshooting guides for common issues [Ory Troubleshooting Index](https://www.ory.sh/docs/troubleshooting). If you provide the full error response body (not just the error type), I can help interpret the specific cause based on the Ory error format. If you need more specific guidance, please share the actual error response payload you received from the Ory API.
c
@chilly-king-10285 Promise { <pending>, [Symbol(async_id_symbol)]: 33983, [Symbol(trigger_async_id_symbol)]: 33604, [Symbol(kResourceStore)]: { isAppRoute: true, isAction: false }, [Symbol(kResourceStore)]: { type: ‘request’, phase: ‘action’, implicitTags: [ ‘_N_T_/layout’, ‘_N_T_/(payload)/layout’, ‘_N_T_/(payload)/api/layout’, ‘_N_T_/(payload)/api/[...slug]/layout’, ‘_N_T_/(payload)/api/[...slug]/route’, ‘_N_T_/api/subscriptions/subscribe’ ], url: { pathname: ‘/api/subscriptions/subscribe’, search: ‘’ }, rootParams: {}, headers: [Getter], cookies: [Getter/Setter], mutableCookies: [Getter], userspaceMutableCookies: [Getter], draftMode: [Getter], renderResumeDataCache: null, isHmrRefresh: false, serverComponentsHmrCache: undefined, usedDynamic: true }, [Symbol(kResourceStore)]: { isStaticGeneration: false, page: ‘/(payload)/api/[...slug]/route’, fallbackRouteParams: null, route: ‘/api/[...slug]’, incrementalCache: IncrementalCache { locks: Map(0) {}, hasCustomCacheHandler: false, dev: true, disableForTestmode: false, minimalMode: false, requestHeaders: [Object], requestProtocol: ‘https’, allowedRevalidateHeaderKeys: undefined, prerenderManifest: [Object], cacheControls: [SharedCacheControls], fetchCacheKeyPrefix: ‘’, cacheHandler: [FileSystemCache] }, cacheLifeProfiles: { default: [Object], seconds: [Object], minutes: [Object], hours: [Object], days: [Object], weeks: [Object], max: [Object] }, isRevalidate: false, isPrerendering: undefined, fetchCache: undefined, isOnDemandRevalidate: undefined, isDraftMode: undefined, requestEndedState: undefined, isPrefetchRequest: undefined, buildId: ‘development’, reactLoadableManifest: {}, assetPrefix: ‘’, afterContext: AfterContext { workUnitStores: Set(0) {}, waitUntil: [Function (anonymous)], onClose: [Function: bound onClose], onTaskError: undefined, callbackQueue: [EventEmitter] }, dynamicIOEnabled: false, dev: false, nextFetchId: 7, fetchMetrics: [ [Object], [Object], [Object], [Object], [Object], [Object] ] } }
b
A message from kapa.ai
I'm sorry, but the information provided in your last message appears to be a debug output or internal state of a Promise object, likely from a Node.js or Next.js application. The knowledge sources do not contain information about interpreting or handling this specific Promise debug output, nor do they provide guidance on this type of runtime object. If your question is about how this relates to Ory or how to handle Promises in the context of Ory's SDKs, please clarify your question or provide more context. Otherwise, based on the knowledge sources, I cannot provide a specific answer regarding this Promise object.
c
@chilly-king-10285 How do I expand this console.log(error) to get any usable informaiton from it: Error [ResponseError]: Response returned an error code at Generator.next (<anonymous>) { response: [Response] }
b
A message from kapa.ai
To extract usable information from an error like
Error [ResponseError]: Response returned an error code
, you should inspect the error's response body, as Ory APIs return detailed error information in a standard JSON format. According to the Ory API reference, the error response typically includes fields such as
error
,
error_description
,
message
, and
status_code
 [Ory API Reference](https://www.ory.sh/docs/reference/api). Here’s how you can expand your error handling to log the detailed error information:
Copy code
typescript try {   // your Ory API call } catch (error: any) {   // Check if the error has a response property (as with Ory's SDKs)   if (error.response) {     // Try to parse the response as JSON     error.response.json().then((body: any) => {       console.error("Ory API error:", body)     }).catch(() => {       // If response is not JSON, log the raw response       console.error("Ory API error (non-JSON):", error.response)     })   } else {     // Fallback for other error types     console.error("Unknown error:", error)   } }
This approach is based on the fact that Ory APIs return errors in a structured JSON format, as described in the documentation. By inspecting the
response
property and parsing it as JSON, you can access the detailed error message, status code, and other useful information for debugging or user feedback. If you need to see the exact structure of the error response, refer to the [Ory API error format](https://www.ory.sh/docs/reference/api), which includes fields like
error
,
error_description
,
message
, and
status_code
. If you need more specific details or encounter a different error structure, please provide the actual error response payload.
c
@chilly-king-10285 Ory API error: { id: ‘f33e2706-0aee-45cd-b72c-ca756935b194’, organization_id: null, type: ‘api’, expires_at: ‘2025-06-12T051708.645832Z’, issued_at: ‘2025-06-12T044708.645832Z’, request_url: ‘https://bold-kepler-liove18x32.projects.oryapis.com/self-service/login/api’, ui: { action: ‘https://bold-kepler-liove18x32.projects.oryapis.com/self-service/login?flow=f33e2706-0aee-45cd-b72c-ca756935b194’, method: ‘POST’, nodes: [ [Object], [Object], [Object], [Object], [Object] ], messages: [ [Object] ] }, created_at: ‘2025-06-12T044708.651358Z’, updated_at: ‘2025-06-12T044708.651358Z’, refresh: false, requested_aal: ‘aal1’, state: ‘choose_method’ }
b
A message from kapa.ai
The error object you posted is not a typical error response, but rather a login flow object returned by the Ory API. This usually happens when the API call was technically successful, but the login flow is not yet complete or requires further user input. Key points from the object: - state: 'choose_method' This means the login flow is waiting for you to choose an authentication method (e.g., password, code, etc.). - ui.messages This array may contain messages (such as errors or instructions) that should be displayed to the user. You should inspect the contents of
ui.messages
for any error or informational messages. Each message typically has an
id
,
text
, and possibly a
type
(such as "error" or "info") [Error handling](https://www.ory.sh/docs/kratos/bring-your-own-ui/custom-ui-basic-integration#error-handling). - ui.nodes This array describes the form fields and UI elements you need to render for the user to proceed with the login flow. - ui.action This is the URL where you should POST the user's credentials or selected method to continue the flow. What to do next: 1. Check
ui.messages
Display or log the messages to see if there are any errors or instructions for the user. 2. Render the UI Use the information in
ui.nodes
to render the login form for the user to select a method and provide credentials. 3. Submit to
ui.action
When the user submits the form, send the data to the
ui.action
URL using the specified HTTP method. Summary: This is not an error in the sense of a failed request, but an indication that the login flow is awaiting user input. You should present the UI described in the response to the user and handle any messages provided in
ui.messages
 [Error handling](https://www.ory.sh/docs/kratos/bring-your-own-ui/custom-ui-basic-integration#error-handling). If you need to see the actual messages or form fields, log or inspect the contents of
ui.messages
and
ui.nodes
in detail.
c
@chilly-king-10285 Ory API error: [ { id: 4010002, text: ‘Could not find a strategy to log you in with. Did you fill out the form correctly?’, type: ‘error’ } ]
b
A message from kapa.ai
The error message
Copy code
{   id: 4010002,   text: "Could not find a strategy to log you in with. Did you fill out the form correctly?",   type: "error" }
means that Ory Kratos could not determine which login strategy (such as password, code, OIDC, etc.) to use based on the data you submitted. This typically happens if the required fields for any enabled login strategy are missing or incorrectly filled out in your request. How to resolve: - Ensure you are submitting all required fields for at least one enabled login strategy. For example, if you are using password login, you must provide both the identifier (such as email or username) and the password. - Double-check the names and values of the fields you are sending match what Ory expects for the enabled strategies in your configuration. You can find this error and its explanation in the Ory documentation: [Could not find a strategy to log you in with. Did you fill out the form correctly? (4010002)](https://www.ory.sh/docs/kratos/concepts/ui-messages#could-not-find-a-strategy-to-log-you-in-with-did-you-fill-out-the-form-correctly-4010002)
c
@chilly-king-10285
@chilly-king-10285 const otc_login_result = await oryFrontendAPI.updateLoginFlow({ flow: flow.id, updateLoginFlowBody: { method: “code”, identifier: identifier, csrf_token: csrf_token } })
b
Sorry @careful-honey-27437, I'm not sure what you mean. Please try again. 👋
A message from kapa.ai
Your code for submitting an OTC (one-time code) login using the Ory TypeScript SDK is almost correct, but based on the knowledge sources, there are a few important points to ensure it works as expected: 1. Required Fields: When using the
code
method for the login flow, the API expects at least the
method
and
csrf_token
fields. The
identifier
is required when requesting the code (first step), and the
code
field is required when submitting the received code (second step). The
csrf_token
must be extracted from the login flow's UI nodes. 2. Extracting the CSRF Token: The CSRF token is found in the
flow.ui.nodes
array, specifically in the node where
attributes.name === "csrf_token"
. The knowledge sources show this pattern, but do not provide a type-safe utility, so you may need to use a type assertion:
Copy code
typescript    const csrf_token = flow.ui.nodes.find(      (node) => (node.attributes as any).name === "csrf_token"    )?.attributes.value
3. Example for Requesting the Code (First Step):
Copy code
typescript    const otc_login_result = await oryFrontendAPI.updateLoginFlow({      flow: flow.id,      updateLoginFlowBody: {        method: "code",        identifier: identifier,        csrf_token: csrf_token,      },    })
This will trigger Ory to send a one-time code to the user. 4. Example for Submitting the Code (Second Step):
Copy code
typescript    const otc_login_result = await oryFrontendAPI.updateLoginFlow({      flow: flow.id,      updateLoginFlowBody: {        method: "code",        code: userInputCode, // The code the user received        csrf_token: csrf_token,      },    })
Important: - If you receive an error like
Could not find a strategy to log you in with. Did you fill out the form correctly?
, it means the required fields for the selected strategy are missing or incorrect. Double-check that you are sending the correct fields for the current step of the flow [see error explanation](https://www.ory.sh/docs/kratos/concepts/ui-messages#could-not-find-a-strategy-to-log-you-in-with-did-you-fill-out-the-form-correctly-4010002). - The knowledge sources do not provide a more type-safe way to extract the CSRF token, nor do they show a different structure for the request body. References: - [Ory API Reference – updateLoginFlow](https://www.ory.sh/docs/reference/api) - [Debug: Cross-site request forgery errors](https://www.ory.sh/docs/kratos/bring-your-own-ui/custom-ui-basic-integration#debug) - [UI error messages](https://www.ory.sh/docs/kratos/concepts/ui-messages#could-not-find-a-strategy-to-log-you-in-with-did-you-fill-out-the-form-correctly-4010002) If you need to see the actual structure of
flow.ui.nodes
, you can log it to inspect the available fields.
c
@chilly-king-10285 I’m trying to initiate an OTC login. The user hasn’t received a code yet because it hasn’t been intitaed yet. What is the method I need to use to create or initiate an OTC login.
b
A message from kapa.ai
To initiate an OTC (one-time code) login in Ory, you need to start a login flow and submit the user's identifier (such as their email or phone number) with the
code
method. This will trigger Ory to send the one-time code to the user. The correct method to use is
code
.
Here’s how the process works: 1. Start a login flow (using the appropriate endpoint for your environment, e.g.,
/self-service/login/api
for API clients). 2. Submit the identifier and method: In the first step, you send a request with: -
method: "code"
-
identifier: "<user's email or phone>"
-
csrf_token
(if required, e.g., for browser flows) Example request body:
Copy code
json    {      "method": "code",      "identifier": "<mailto:user@example.com|user@example.com>",      "csrf_token": "<csrf_token>"    }
This will initiate the OTC login and send the code to the user. This flow is described in the documentation: > In the first step the user is required to enter their email address or phone number. In the second step they are prompted to enter the one-time code sent to their email address or phone number [Email and SMS one-time-code authentication](https://www.ory.sh/docs/kratos/passwordless/one-time-code). So, to initiate an OTC login, use the
code
method and provide the user's identifier in your call to the login flow endpoint.
c
@chilly-king-10285 Which typescript SDK API shoudl I use?
b
A message from kapa.ai
To initiate an OTC (one-time code) login using TypeScript, you should use the
@ory/client
SDK. The official Ory documentation provides TypeScript examples using this SDK for interacting with Ory flows, including login and passwordless flows. The
@ory/client-fetch
package is also mentioned for React and API integration, but the primary and most documented SDK is
@ory/client
 [Docs > Kratos > Bring-your-own-ui > Integration basics > Login flow](https://www.ory.sh/docs/kratos/bring-your-own-ui/custom-ui-basic-integration#get-login-flow). Summary: - Use the
@ory/client
TypeScript SDK for initiating and managing OTC login flows in Ory. If you are building a React or browser-based app, you may also see references to
@ory/client-fetch
, but the main SDK for TypeScript usage is
@ory/client
.