LangGraph Tutorial (TypeScript): building conditional routing for advanced developers
This tutorial shows how to build a LangGraph workflow in TypeScript that routes requests conditionally between different nodes based on state. You need this when a single linear chain is not enough and your agent has to choose different paths for classification, tool use, escalation, or fallback handling.
What You'll Need
- •Node.js 18+
- •TypeScript 5+
- •
@langchain/langgraph - •
@langchain/core - •An OpenAI API key if you want to extend this into an LLM-backed router
- •A working TypeScript runtime such as
tsxorts-node
Install the packages:
npm install @langchain/langgraph @langchain/core
npm install -D typescript tsx @types/node
Step-by-Step
- •Start with a typed state model and import the graph primitives.
The key idea is to keep routing decisions inside state, not scattered across ad hoc conditionals.
import { StateGraph, START, END } from "@langchain/langgraph";
type RouteState = {
input: string;
route?: "billing" | "support" | "fallback";
result?: string;
};
- •Add nodes that represent the possible branches.
Each node should do one thing and return partial state updates.
const classifyNode = async (state: RouteState): Promise<Partial<RouteState>> => {
const text = state.input.toLowerCase();
if (text.includes("invoice") || text.includes("payment")) {
return { route: "billing" };
}
if (text.includes("password") || text.includes("login")) {
return { route: "support" };
}
return { route: "fallback" };
};
const billingNode = async (): Promise<Partial<RouteState>> => ({
result: "Billing team handles invoices, refunds, and payment failures.",
});
const supportNode = async (): Promise<Partial<RouteState>> => ({
result: "Support team handles login issues, access resets, and account help.",
});
const fallbackNode = async (): Promise<Partial<RouteState>> => ({
result: "Route unclear. Escalate to a human triage queue.",
});
- •Define the conditional routing function.
This is where LangGraph decides which edge to follow after classification.
const routeByDecision = (state: RouteState) => {
switch (state.route) {
case "billing":
return "billing";
case "support":
return "support";
default:
return "fallback";
}
};
- •Build the graph and connect the conditional edges.
The important part is thataddConditionalEdgesmaps router outputs to node names explicitly.
const graph = new StateGraph<RouteState>()
.addNode("classify", classifyNode)
.addNode("billing", billingNode)
.addNode("support", supportNode)
.addNode("fallback", fallbackNode)
.addEdge(START, "classify")
.addConditionalEdges("classify", routeByDecision, {
billing: "billing",
support: "support",
fallback: "fallback",
})
.addEdge("billing", END)
.addEdge("support", END)
.addEdge("fallback", END);
- •Compile and run the workflow with a few test inputs.
This gives you a deterministic router that you can later replace with an LLM classifier or policy engine.
const app = graph.compile();
async function main() {
const cases = [
{ input: "I can't log in to my account" },
{ input: "Where is my invoice?" },
{ input: "I need help with something else" },
];
for (const testCase of cases) {
const output = await app.invoke(testCase);
console.log({
input: testCase.input,
route: output.route,
result: output.result,
});
}
}
main();
Testing It
Run the file with npx tsx your-file.ts. You should see each input routed to the correct branch and returning a different result value.
If you get undefined routes, check that your classifier node returns one of the exact keys used in routeByDecision and the conditional edge map. In LangGraph, string mismatches are the most common reason routing breaks.
For production use, add unit tests around the router function first. That function is pure, so it’s easy to test without compiling the whole graph.
Next Steps
- •Replace the keyword-based classifier with an LLM node that returns structured routing decisions.
- •Add a human escalation branch with audit logging for regulated workflows.
- •Introduce loopbacks for retry logic when downstream tools fail or confidence is low.
Keep learning
- •The complete AI Agents Roadmap — my full 8-step breakdown
- •Free: The AI Agent Starter Kit — PDF checklist + starter code
- •Work with me — I build AI for banks and insurance companies
By Cyprian Aarons, AI Consultant at Topiax.
Want the complete 8-step roadmap?
Grab the free AI Agent Starter Kit — architecture templates, compliance checklists, and a 7-email deep-dive course.
Get the Starter Kit