Try it yourself with our free Html Beautifier tool — runs entirely in your browser, no signup needed.

How to Format HTML for API Responses

How to format HTML for API Responses

When building web applications, it's common to consume data from APIs and render it on the client-side. However, API responses often contain plain text or JSON data, which needs to be formatted as HTML to be displayed on the page. In this article, we'll explore how to format HTML for API responses, providing a practical guide with code examples and best practices.

Quick Example

Here's a minimal example in JavaScript using the DOMParser API to parse a string of HTML and render it on the page:

// Install the DOMParser polyfill if needed
// npm install dom-parser
import { DOMParser } from 'dom-parser';

const apiResponse = '<p>Hello, <strong>World!</strong></p>';
const parser = new DOMParser();
const doc = parser.parseFromString(apiResponse, 'text/html');
const htmlElement = doc.body.firstChild;

document.getElementById('container').appendChild(htmlElement);

This example assumes you have a container element on the page where the formatted HTML will be rendered.

Real-World Scenarios

Scenario 1: Rendering User-Generated Content

When allowing users to input HTML content, it's essential to sanitize and format the input to prevent XSS attacks. Here's an example using the DOMParser API and a sanitization library like DOMPurify:

import { DOMParser } from 'dom-parser';
import DOMPurify from 'dompurify';

const userInput = '<p>Hello, <script>alert("XSS")</script> World!</p>';
const sanitizedInput = DOMPurify.sanitize(userInput);
const parser = new DOMParser();
const doc = parser.parseFromString(sanitizedInput, 'text/html');
const htmlElement = doc.body.firstChild;

document.getElementById('container').appendChild(htmlElement);

Scenario 2: Handling Nested HTML Structures

When working with nested HTML structures, it's crucial to ensure that the inner HTML is properly formatted. Here's an example using the innerHTML property:

const apiResponse = '<div><p>Hello, <span>World!</span></p></div>';
const container = document.getElementById('container');
container.innerHTML = apiResponse;

Scenario 3: Supporting Older Browsers

When supporting older browsers that don't support the DOMParser API, you can use the innerHTML property as a fallback:

const apiResponse = '<p>Hello, <strong>World!</strong></p>';
const container = document.getElementById('container');

if (window.DOMParser) {
  const parser = new DOMParser();
  const doc = parser.parseFromString(apiResponse, 'text/html');
  const htmlElement = doc.body.firstChild;
  container.appendChild(htmlElement);
} else {
  container.innerHTML = apiResponse;
}

Best Practices

  1. Use the DOMParser API: When possible, use the DOMParser API to parse and format HTML responses, as it provides a more secure and efficient way to handle HTML content.
  2. Sanitize user-generated content: Always sanitize user-generated content to prevent XSS attacks.
  3. Use the innerHTML property with caution: When using the innerHTML property, be aware of potential security risks and ensure that the content is properly sanitized.
  4. Support older browsers: When supporting older browsers, use feature detection to determine the best approach for formatting HTML responses.
  5. Test thoroughly: Always test your implementation thoroughly to ensure that it works as expected across different browsers and scenarios.

Common Mistakes

Mistake 1: Not sanitizing user-generated content

Wrong code:

const userInput = '<p>Hello, <script>alert("XSS")</script> World!</p>';
document.getElementById('container').innerHTML = userInput;

Corrected code:

import DOMPurify from 'dompurify';

const userInput = '<p>Hello, <script>alert("XSS")</script> World!</p>';
const sanitizedInput = DOMPurify.sanitize(userInput);
document.getElementById('container').innerHTML = sanitizedInput;

Mistake 2: Not handling nested HTML structures

Wrong code:

const apiResponse = '<div><p>Hello, <span>World!</span></p></div>';
const container = document.getElementById('container');
container.appendChild(apiResponse);

Corrected code:

const apiResponse = '<div><p>Hello, <span>World!</span></p></div>';
const container = document.getElementById('container');
container.innerHTML = apiResponse;

Mistake 3: Not supporting older browsers

Wrong code:

const apiResponse = '<p>Hello, <strong>World!</strong></p>';
const container = document.getElementById('container');
const parser = new DOMParser();
const doc = parser.parseFromString(apiResponse, 'text/html');
const htmlElement = doc.body.firstChild;
container.appendChild(htmlElement);

Corrected code:

const apiResponse = '<p>Hello, <strong>World!</strong></p>';
const container = document.getElementById('container');

if (window.DOMParser) {
  const parser = new DOMParser();
  const doc = parser.parseFromString(apiResponse, 'text/html');
  const htmlElement = doc.body.firstChild;
  container.appendChild(htmlElement);
} else {
  container.innerHTML = apiResponse;
}

FAQ

Q: What is the DOMParser API?

The DOMParser API is a web API that allows you to parse a string of HTML or XML and create a Document object.

Q: How do I sanitize user-generated content?

You can use a library like DOMPurify to sanitize user-generated content and prevent XSS attacks.

Q: What is the difference between innerHTML and DOMParser?

innerHTML is a property that sets or gets the HTML content of an element, while DOMParser is an API that parses a string of HTML or XML and creates a Document object.

Q: How do I support older browsers?

You can use feature detection to determine the best approach for formatting HTML responses, and provide a fallback for older browsers that don't support the DOMParser API.

Q: What are some common mistakes when formatting HTML responses?

Common mistakes include not sanitizing user-generated content, not handling nested HTML structures, and not supporting older browsers.

AI agent tools available. The CodeTidy MCP Server gives Claude, Cursor, and other AI agents access to 60+ developer tools. One command: npx @codetidy/mcp