Understanding HTTP Content-Type



This content originally appeared on DEV Community and was authored by FakeStandard

The HTTP Content-Type header tells the server or browser what kind of data is begin sent and how it’s encoded. Setting the correct Content-Type makes sure both the client and server understand each other — it also helps the browser handle data safely and efficiently.

When a client (like your browser or app) sends a request, it should include a Content-Type so the server knows how to read the data. Likewise, when the server sends a response back, it should also specify the Content-Type so the client knows how to process or display it.

🔅 The Structure of Content-Type

A Content-Type header is made up of a MIME type and (optionally) a charset for encoding

Content-Type: <mime-type>[; charset=<encoding>]

Example

Content-Type: text/html; charset=utf-8
  • text/html — MIME type
  • charset=utf8 — character encoding

When the browser receives a response with Content-Type: text/html, it knows to render it as an HTML page.
If it’s image/jpeg, the browser knows it’s an image and display it instead.

🔍 What’s a MIME Type?

A MIME type is a standardized way to describe different types of data on the web. You can find the full official list here IANA Media Types

Common Content-Type Values in Web Development

Content-Type Description
text/html HTML document
text/plain Plain text
text/xml XML data
image/gif GIF image
image/jpeg JPEG image
image/png PNG image
application/json JSON data
application/pdf PDF document
application/msword Word document
application/octet-stream Binary data
application/x-www-form-urlencoded Default format for HTML forms
multipart/form-data Used for file uploads

🍵 Setting Headers with Fetch API

When you send data using Fetch API, you can set the Content-Type in the request headers.
Here’s a simple example of sending JSON data to server

fetch(url, {
    method: 'POST',
    body: JSON.stringify(data),
    headers: {
        'content-type': 'application/json',
    }
})
    .then((res) => res.json())
    .then((response) => console.log("Success:", response))
    .catch((error) => console.error("Error:", error));
  • We convert data to JSON before sending (JSON.stringify())
  • The header Content-Type: 'application/json' tells the server we’re sending JSON
  • The server can then parse it properly using a JSON parser.

Easy fix. Job done ☑

Thanks for reading!

If you like this article, please don’t hesitate to click the heart button ❤
or follow my GitHub I’d appreciate it.


This content originally appeared on DEV Community and was authored by FakeStandard