How to Write Quality Documentation

By X402 Team | Last Updated: February 2026

Goal

Create clear, accurate, and user-friendly documentation that helps readers accomplish their goals quickly and confidently.

What You'll Achieve

  • Understanding of documentation quality principles
  • Practical writing techniques for clarity
  • Structure that serves your audience
  • Methods to verify documentation quality
  • Habits that improve writing over time

Prerequisites

  • Content topic identified
  • Target audience understood
  • X402 batch created (see "How to Create Your First Batch")
  • Text editor ready
  • 30-60 minutes available

Time Required

Learning: 10 minutes (reading this guide) Applying: 30-60 minutes per documentation piece Improving: Ongoing with each piece you write

Core Principles of Quality Documentation

Principle 1: Know Your Audience

Before writing, answer:

  • Who will read this?
  • What do they already know?
  • What do they need to learn?
  • How will they use this information?

Example:

Bad (no audience focus):

# Authentication
The system uses OAuth 2.0.

Good (audience-focused):

# Authentication for Developers

If you're integrating our API, you'll use OAuth 2.0 for authentication. This guide assumes you're familiar with REST APIs but new to OAuth.

You'll learn:

  • How to register your application (5 minutes)
  • How to obtain access tokens (10 minutes)
  • How to make authenticated requests (5 minutes)

Principle 2: Write for Scannability

Readers scan before they read. Help them:

  • Use descriptive headings
  • Break content into short paragraphs (3-4 lines max)
  • Use bullet points and numbered lists
  • Highlight important information
  • Add code examples and visuals

Example:

Bad (wall of text):

To install the software, first you need to download it from our website and then extract the archive file to your preferred location on your computer. After that, you should run the installer executable and follow the on-screen prompts to complete the installation process. Make sure you have administrator privileges before starting.

Good (scannable):

## Installation Steps

Prerequisites: Administrator access to your computer

  1. Download the installer from our website
  2. Extract the archive to your preferred location
  3. Run the installer executable
  4. Follow the on-screen prompts

Installation takes approximately 5 minutes.

Principle 3: Be Specific and Concrete

Use precise language instead of vague descriptions.

Vague:

  • "The system is fast"
  • "Installation is easy"
  • "Contact support if needed"

Specific:

  • "API responses return in under 200ms"
  • "Installation takes 3 steps and 5 minutes"
  • "Email support@example.com or call 1-800-555-0123 (Mon-Fri, 9am-5pm EST)"

Principle 4: Show, Don't Just Tell

Include examples, code snippets, and screenshots.

Tell only:

Use the API to create a user.

Show and tell:

## Creating a User

Send a POST request to /api/users with user details:

bash curl -X POST https://api.example.com/users \ -H "Content-Type: application/json" \ -d '{ "name": "John Doe", "email": "john@example.com" }'

Response:
json { "id": "usr_123", "name": "John Doe", "email": "john@example.com", "created_at": "2024-11-23T10:30:00Z" }

Step-by-Step Documentation Process

Step 1: Plan Your Structure (5 minutes)

Create an outline before writing:

# [Document Title] — Outline

Sections to include:

  1. Overview (what and why)
  2. Prerequisites (what readers need first)
  3. Main content (how to do it)
  4. Examples (show it working)
  5. Troubleshooting (common issues)
  6. Next steps (what's next)

Audience notes:

  • Level: Intermediate developers
  • Goal: Successfully authenticate API requests
  • Time: Should complete in 15 minutes

Step 2: Write a Strong Opening (5 minutes)

First paragraph should answer: What, Why, Who

Template:

# [Clear, Descriptive Title]

Overview

This guide explains [WHAT] for [WHO]. You'll learn [KEY BENEFITS].

[WHY this matters or when to use it]

Time required: [X minutes] Difficulty: [Beginner/Intermediate/Advanced]

Example:

# JWT Authentication — Quick Start Guide

Overview

This guide explains how to use JWT tokens for API authentication for backend developers. You'll learn how to generate, validate, and use JWTs in your application.

JWT authentication is ideal when you need stateless authentication that scales across multiple servers without session storage.

Time required: 20 minutes Difficulty: Intermediate

Step 3: Write Clear Instructions (20-30 minutes)

For Tutorials/How-Tos:

Use numbered steps:

## Implementation Steps

1. Install Required Package

bash npm install jsonwebtoken

This adds JWT functionality to your Node.js application.

2. Generate Secret Key

bash node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"

Save this key securely in your environment variables:
bash export JWT_SECRET="your_generated_key_here"

3. Create Token Generation Function

javascript const jwt = require('jsonwebtoken');

function generateToken(userId) { return jwt.sign( { userId: userId }, process.env.JWT_SECRET, { expiresIn: '1h' } ); }


This function creates a token that expires in 1 hour.

For Reference Documentation:

Use clear structure with examples:

## Function: generateToken()

Generates a JWT token for authenticated users.

Syntax

javascript generateToken(userId, options)

Parameters

  • userId (string, required): Unique identifier for the user
  • options (object, optional):
  • expiresIn (string): Token expiration time (default: '1h')
  • algorithm (string): Signing algorithm (default: 'HS256')

Returns

String: Encoded JWT token

Example

javascript const token = generateToken('user_123', { expiresIn: '24h' }); console.log(token); // Output: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

Throws

  • Error: If userId is not provided
  • Error: If JWT_SECRET environment variable is missing

Step 4: Add Examples (10 minutes)

Include multiple examples for different scenarios:

## Examples

Basic Usage

javascript // Simple token generation const token = generateToken('user_123');

With Custom Expiration

javascript // Token that expires in 7 days const token = generateToken('user_123', { expiresIn: '7d' });

With Additional Claims

javascript // Include user role in token const token = jwt.sign( { userId: 'user_123', role: 'admin', permissions: ['read', 'write'] }, process.env.JWT_SECRET, { expiresIn: '1h' } );

Complete Authentication Flow

javascript // Login endpoint app.post('/login', async (req, res) => { const { email, password } = req.body;

// Verify credentials (implementation not shown) const user = await verifyCredentials(email, password);

if (!user) { return res.status(401).json({ error: 'Invalid credentials' }); }

// Generate token const token = generateToken(user.id);

res.json({ token }); });

// Protected endpoint app.get('/profile', authenticateToken, (req, res) => { res.json({ userId: req.user.userId }); });

Step 5: Add Troubleshooting Section (5-10 minutes)

Document common issues you've encountered:

## Troubleshooting

"JsonWebTokenError: invalid signature"

Cause: Token was signed with different secret key

Solution: Ensure JWT_SECRET environment variable matches between token generation and verification:

bash

Check your secret

echo $JWT_SECRET

Regenerate token with correct secret


"TokenExpiredError: jwt expired"

Cause: Token lifetime exceeded

Solution: Request a new token by re-authenticating:

javascript // Check token expiration before using const decoded = jwt.decode(token); const isExpired = decoded.exp < Date.now() / 1000;

if (isExpired) { // Refresh or re-authenticate }


Token validation passes but user is unauthorized

Cause: Token contains valid signature but outdated user permissions

Solution: Implement token refresh on permission changes:

javascript // In your database update async function updateUserRole(userId, newRole) { await db.users.update(userId, { role: newRole }); await invalidateExistingTokens(userId); // Force re-authentication }

Still having issues?

  1. Check server logs for detailed error messages
  2. Verify token format: header.payload.signature
  3. Test with jwt.io debugger
  4. Review JWT specification
  5. Contact support with request ID

Writing Style Guidelines

Use Active Voice

Passive: "The token should be sent in the Authorization header" ✅ Active: "Send the token in the Authorization header"

Passive: "Errors can be handled by implementing try-catch" ✅ Active: "Handle errors by implementing try-catch"

Write in Second Person ("You")

Third person: "Developers should install the SDK" ✅ Second person: "Install the SDK"

Third person: "Users can configure settings in the dashboard" ✅ Second person: "Configure your settings in the dashboard"

Use Simple, Direct Language

Complex: "Utilize the aforementioned methodology to facilitate token-based authentication" ✅ Simple: "Use this method to enable token authentication"

Complex: "Prior to commencing implementation" ✅ Simple: "Before you start"

Be Consistent

Pick conventions and stick to them:

  • Code style: camelCase vs snake_case
  • Formatting: "Step 1" vs "Step 1:"
  • Terminology: "function" vs "method" (be consistent)
  • Examples: Always use same example app/user

Quality Checklist

Before marking documentation complete:

Content Quality

  • [ ] Accurate: All information is correct and up-to-date
  • [ ] Complete: All necessary information is included
  • [ ] Clear: No ambiguous or confusing statements
  • [ ] Tested: All code examples work as written
  • [ ] Relevant: Stays focused on the topic

Structure Quality

  • [ ] Logical flow: Information in sensible order
  • [ ] Proper headings: Hierarchy makes sense (H1 > H2 > H3)
  • [ ] Scannable: Easy to find information quickly
  • [ ] Linked: Related content is cross-referenced

Technical Quality

  • [ ] Code examples: Present and working
  • [ ] Error handling: Common issues addressed
  • [ ] Prerequisites: Clearly stated
  • [ ] Next steps: Provided

Writing Quality

  • [ ] Grammar: No grammatical errors
  • [ ] Spelling: No typos
  • [ ] Consistent: Style is consistent throughout
  • [ ] Concise: No unnecessary wordiness

User Experience

  • [ ] Helpful: Solves user's problem
  • [ ] Accessible: Appropriate for target audience
  • [ ] Actionable: User knows what to do next
  • [ ] Complete: User can accomplish goal

Testing Your Documentation

Self-Test Method

Follow your own instructions:

  1. Open your documentation
  2. Follow each step exactly as written
  3. Note where you get confused or stuck
  4. Revise those sections

Fresh Eyes Test

Ask someone else to follow your docs:

  1. Find someone in your target audience
  2. Have them complete the task using only your docs
  3. Watch where they struggle (don't help!)
  4. Revise based on their experience

Metrics to Track

Measure documentation effectiveness:

  • Time to complete: Target vs actual
  • Success rate: % who complete successfully
  • Questions asked: Where do users get stuck?
  • Feedback ratings: "Was this helpful?"

Tools for Quality Documentation

Grammar and Style

# Install writing assistants
npm install -g write-good
npm install -g alex

Check your writing

write-good documentation.md alex documentation.md

Spell Checking

# Install cspell
npm install -g cspell

Check spelling

cspell batch-/\.md

Add custom words

echo "JWT" >> .cspell-words.txt

Link Validation

# Install markdown-link-check
npm install -g markdown-link-check

Check all links

markdown-link-check documentation.md

Readability Analysis

# Install readability tools
npm install -g readability-cli

Check readability score

readability documentation.md

Aim for:

- Flesch Reading Ease: 60-70

- Grade Level: 8-10

Continuous Improvement

After Publishing

Gather feedback:

# Add to end of documentation

Was this helpful?

👍 Yes | 👎 No

Tell us how we can improve this page

Common Questions

(Add questions from users as they come in)

Review Cycle

Schedule regular reviews:

  • Weekly: Check recent user questions
  • Monthly: Review page analytics
  • Quarterly: Full documentation audit
  • After updates: Update docs when product changes

Learn from Analytics

Track what users do:

  • Most visited pages (what's important)
  • Exit pages (where users get stuck)
  • Search terms (what users look for)
  • Time on page (too long = confusing)

Quick Reference

Good Documentation Has

✅ Clear, descriptive title ✅ Brief overview explaining what/why/who ✅ Prerequisites listed upfront ✅ Step-by-step instructions ✅ Working code examples ✅ Troubleshooting section ✅ Next steps or related content ✅ No spelling or grammar errors

Common Mistakes to Avoid

❌ Assuming too much knowledge ❌ Using jargon without explanation ❌ Skipping error scenarios ❌ No examples or only trivial examples ❌ Outdated screenshots or information ❌ Broken links ❌ Inconsistent terminology ❌ No way to provide feedback

Templates for Common Documentation Types

Tutorial Template

# [Tutorial Title] — Tutorial

What You'll Build

[Description of end result]

Prerequisites

  • [Requirement 1]
  • [Requirement 2]

Step 1: [First Step]

[Instructions]
code [Code example]

Step 2: [Second Step]

...

Verification

[How to confirm it works]

Next Steps

[What to learn next]

Concept Guide Template

# [Concept Name] — Concept Guide

What Is [Concept]?

[Definition]

Why [Concept] Matters

[Importance and use cases]

How [Concept] Works

[Explanation with diagram]

Key Terminology

  • Term 1: Definition
  • Term 2: Definition

Best Practices

[Recommendations]

Related Concepts

[Cross-references]

Reference Template

# [API/Function Name] — Reference

Description

[What it does]

Syntax

[Code signature]

Parameters

[Detailed parameter descriptions]

Returns

[Return value description]

Examples

[Multiple examples]

Error Handling

[Possible errors]

See Also

[Related functions]

Related Guides

  • How to Create Your First Batch
  • X402 Templates Guide
  • X402 Best Practices
  • X402 for Documentation Teams

Quality Standards

  • [x] Clear principles explained
  • [x] Actionable techniques provided
  • [x] Examples demonstrate concepts
  • [x] Quality checklist included
  • [x] Tools and resources listed
  • [x] Templates provided
  • [x] Ready for production

Start Building with X402

Get our free X402 Implementation Starter Kit with ready-to-use templates, code examples, and best practices.

What is included:

  • Quick-start implementation templates
  • API integration examples
  • Configuration best practices guide

Get the Free Starter Kit