Mastering Output Parsers in LangChain.js
Aug 7,2026

So far in this series, we've learned how to:

  • Build AI applications using LangChain
  • Work with Chat Models
  • Create reusable prompts with PromptTemplate
  • Build conversational prompts with ChatPromptTemplate

All of these examples have one thing in common.

The AI returns a response as plain text.

For example:

Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine...

This works well when displaying content to users.

But what if you're building:

  • A React application
  • A REST API
  • An admin dashboard
  • A chatbot
  • A mobile application

In these cases, plain text isn't always enough.

You often need structured data that your application can easily process.

This is where Output Parsers become useful.

In this article, you'll learn:

  • What Output Parsers are
  • Why we need them
  • StringOutputParser
  • StructuredOutputParser
  • Zod Schema
  • getFormatInstructions()
  • OpenAI examples
  • Gemini examples
  • Best practices

Let's get started.


What is an Output Parser?

An Output Parser transforms the raw response from an AI model into a format that's easier for your application to use.

Without an Output Parser:

User

↓

Prompt

↓

LLM

↓

Plain Text

With an Output Parser:

User

↓

Prompt

↓

LLM

↓

Output Parser

↓

Structured Data

Instead of manually processing the AI response, LangChain can do it for you.


Why Do We Need Output Parsers?

Imagine you ask the AI:

Generate details about Node.js.

The response might be:

Node.js was created by Ryan Dahl in 2009. It uses JavaScript and runs on the V8 engine.

This is easy for humans to read.

But if your application needs to display the creator, release year, and language in separate UI components, parsing plain text becomes difficult.

Instead, you want:

{
  "name": "Node.js",
  "creator": "Ryan Dahl",
  "releaseYear": 2009,
  "language": "JavaScript"
}

Structured output is much easier to consume programmatically.


Project Setup

Install the required packages.

npm install langchain @langchain/openai @langchain/google-genai zod dotenv

Project Structure

output-parsers/

│── index.js
│── .env
│── package.json

Configure Environment Variables

OPENAI_API_KEY=your_openai_api_key
GOOGLE_API_KEY=your_google_api_key

Import Required Modules

import "dotenv/config";

import { z } from "zod";

import { ChatOpenAI } from "@langchain/openai";

import { ChatGoogleGenerativeAI } from "@langchain/google-genai";

import { PromptTemplate } from "@langchain/core/prompts";

import {
  StringOutputParser,
  StructuredOutputParser,
} from "@langchain/core/output_parsers";

Initialize OpenAI

const openAIModel = new ChatOpenAI({
  model: "gpt-4.1-mini",
});

Initialize Gemini

const geminiModel =
  new ChatGoogleGenerativeAI({
    model: "gemini-2.5-flash",
  });

What is StringOutputParser?

StringOutputParser is the simplest output parser in LangChain.

It extracts only the generated text from the AI response.

Normally:

const response =
  await openAIModel.invoke(
    "Explain Node.js."
  );

console.log(response);

The response is an AI message object containing metadata and content.

Most of the time, you only need the text.


Using StringOutputParser

const parser =
  new StringOutputParser();

const chain =
  openAIModel.pipe(parser);

const response =
  await chain.invoke(
    "Explain Node.js."
  );

console.log(response);

Output:

Node.js is a JavaScript runtime...

Notice that the parser returns a plain string instead of an AI message object.


StringOutputParser with Gemini

const parser =
  new StringOutputParser();

const chain =
  geminiModel.pipe(parser);

const response =
  await chain.invoke(
    "Explain React."
  );

console.log(response);

Again, the parser returns only the generated text.


When Should You Use StringOutputParser?

Use it when you need:

  • Plain text responses
  • Blog generation
  • Article summaries
  • Email drafting
  • Chatbot replies
  • Documentation generation

What is StructuredOutputParser?

Sometimes plain text isn't enough.

Suppose you ask the AI:

Generate employee information.

Instead of text, you want:

{
  "name": "John",
  "role": "Frontend Developer",
  "experience": 5
}

This is where StructuredOutputParser comes in.

It instructs the model to return data in a structured format.


What is Zod?

Zod is a schema validation library.

It lets you describe the exact structure you expect from the AI.

Example:

const employeeSchema = z.object({
  name: z.string(),

  role: z.string(),

  experience: z.number(),
});

This schema tells LangChain what the response should look like.


Creating a StructuredOutputParser

const parser =
  StructuredOutputParser.fromZodSchema(
    employeeSchema
  );

Now the parser knows how to validate the response.


Understanding getFormatInstructions()

This is one of the most important methods.

const instructions =
  parser.getFormatInstructions();

console.log(instructions);

The parser generates instructions like:

Return a JSON object matching this schema...

These instructions are added to your prompt so the model knows the expected format.


Creating a PromptTemplate

const prompt =
  PromptTemplate.fromTemplate(`
Generate employee information.

{formatInstructions}
`);

Notice the placeholder:

{formatInstructions}

This tells the model exactly how to format the response.


Open Ai Example

import { StructuredOutputParser } from "@langchain/core/output_parsers";
import { z } from "zod";
import { ChatOpenAI } from "@langchain/openai";
import { PromptTemplate } from "@langchain/core/prompts";

// Define schema
const schema = z.object({
  answer: z.string().describe("answer to the user's question"),
  sources: z.array(z.string()).describe("sources used to answer the question"),
});

// Create parser
const parser = StructuredOutputParser.fromZodSchema(schema);

// Create chain
const chain = PromptTemplate.fromTemplate(
  "Answer the question as best as possible.\n{format_instructions}\n{question}"
)
  .pipe(new ChatOpenAI({ temperature: 0 }))
  .pipe(parser);

const result = await chain.invoke({
  question: "What is the capital of France?",
  format_instructions: parser.getFormatInstructions(),
});   

Gemini Example

import { StructuredOutputParser } from "@langchain/core/output_parsers";
import { z } from "zod";
import { ChatGoogleGenerativeAI } from "@langchain/google-genai";
import { PromptTemplate } from "@langchain/core/prompts";

// Define schema
const schema = z.object({
  answer: z.string().describe("answer to the user's question"),
  sources: z
    .array(z.string())
    .describe("sources used to answer the question"),
});

// Create parser
const parser = StructuredOutputParser.fromZodSchema(schema);

// Create Gemini model
const model = new ChatGoogleGenerativeAI({
  model: "gemini-2.5-flash",
  temperature: 0,
});

// Create chain
const chain = PromptTemplate.fromTemplate(
  "Answer the question as best as possible.\n{format_instructions}\n{question}"
)
  .pipe(model)
  .pipe(parser);

// Invoke chain
const result = await chain.invoke({
  question: "What is the capital of France?",
  format_instructions: parser.getFormatInstructions(),
});

console.log(result);

Real-World Example: Resume Parser

const resumeSchema =
  z.object({
    name: z.string(),
    skills: z.array(z.string()),
    experience: z.number(),
  });

The AI can now return structured resume data that your application can display or store.


Real-World Example: Blog Metadata

const blogSchema =
  z.object({
    title: z.string(),
    description: z.string(),
    tags: z.array(z.string()),
  });

This is useful for automatically generating SEO metadata.


Real-World Example: Product Information

const productSchema =
  z.object({
    name: z.string(),
    price: z.number(),
    category: z.string(),
  });

Instead of parsing text manually, your application receives structured product details.


Best Practices

  • Use StringOutputParser when you only need text.
  • Use StructuredOutputParser when your application needs structured data.
  • Define clear Zod schemas with meaningful field names.
  • Always include parser.getFormatInstructions() in your prompt.
  • Keep schemas simple and focused on the required data.

Common Beginner Mistakes

  • Forgetting to include formatInstructions in the prompt.
  • Expecting the model to return valid JSON without guidance.
  • Creating overly complex schemas for simple tasks.
  • Parsing raw text manually instead of using StructuredOutputParser.
  • Confusing StringOutputParser with StructuredOutputParser.

Final Thoughts

Output Parsers are an important part of LangChain because they bridge the gap between AI-generated text and application-friendly data.

StringOutputParser is perfect for extracting plain text, while StructuredOutputParser combined with Zod enables you to define and validate structured JSON responses.

Understanding these concepts will make it much easier to build reliable AI applications that integrate cleanly with frontends, APIs, and databases.

In the next article, we'll build on this foundation by exploring withStructuredOutput(), a modern approach that simplifies structured response generation even further.

Happy Coding! 🚀