# Content types

> How the server tells the client what's in the body.

Source: https://aminbytes.dev/bytes/http/responses/content-types/


A response body is just bytes. The `Content-Type` header tells the client how to interpret them.

```http {hl_lines="2"}
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Content-Length: 52

{"id": 7, "title": "Learn HTTP", "completed": false}
```

## Common types

| Content-Type               | What's in the body |
| -------------------------- | ------------------ |
| `text/html`                | A web page |
| `text/css`                 | A stylesheet |
| `text/javascript`          | A script |
| `application/json`         | JSON data |
| `image/png`, `image/webp`  | Images |
| `application/pdf`          | A PDF document |
| `application/octet-stream` | "Just bytes", usually triggers a download |

The same bytes can mean different things. Serve `<h1>Hi</h1>` as `text/html` and the browser renders a heading; serve it as `text/plain` and you see the tags.

> [!WARNING]
> If you set the wrong type, browsers may refuse the file. A script served as `text/plain` won't run. A missing type can make some browsers guess (*"sniff"*), which is why servers also send `X-Content-Type-Options: nosniff`.

## Content negotiation

The client says what it prefers with `Accept`; the server picks the best match. That's called content negotiation:

```bash
curl -H "Accept: application/json" https://httpbin.org/get
```

Some APIs return HTML to browsers and JSON to code from the same URL this way.

## Reading the body in JavaScript

`fetch` gives you methods for each kind of body:

```js
const res = await fetch(url);

const type = res.headers.get("Content-Type") ?? "";
if (type.includes("application/json")) {
  const data = await res.json();    // parsed object
} else if (type.startsWith("text/")) {
  const text = await res.text();    // string
} else {
  const blob = await res.blob();    // binary, e.g. an image
}
```

> [!NOTE]
> A body can only be read once. Calling `res.json()` after `res.text()` throws. Use `res.clone()` if you need it twice.


## Byte check

1. The server sends `<h1>Hi</h1>` with `Content-Type: text/plain`. What do you see?
   - A big heading
   - **The tags themselves, as text** (correct)
   - Nothing
   The same bytes mean different things. The type decides how they're shown.

2. Which **request** header asks the server for a specific format?
   - **`Accept`** (correct)
   - `Content-Type`
   - `X-Content-Type-Options`
   That's content negotiation: the server picks the best match from your `Accept` list.

3. You call `res.text()` and then `res.json()` on the same response. What happens?
   - You get both
   - **The second call throws: a body can only be read once** (correct)
   - `json()` reuses the text
   Use `res.clone()` if you really need to read it twice.


