Quick answer: use application/json. It's the official IANA-registered MIME
type for JSON (RFC 4627 / RFC 8259), and every modern client and framework expects it.
Content-Type: application/json
Why you'll see other values floating around
Before application/json was standardized, people experimented with
text/javascript, application/x-javascript, and text/x-json. None of
these are correct today — they're legacy artifacts from before the JSON MIME type was ratified, and
some browsers historically handled them inconsistently.
Setting it correctly in common stacks
// Node / Express
res.setHeader('Content-Type', 'application/json');
res.json(data); // sets the header for you
// PHP
header('Content-Type: application/json');
// fetch() request
fetch(url, {
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
});
What about JSONP?
If you're serving runnable JavaScript that wraps JSON in a callback (JSONP — largely obsolete now
that CORS exists), the correct type is application/javascript, not
application/json, since the response is actual executable script, not pure data.
Does the content type include a charset?
JSON's default encoding is UTF-8, so you generally don't need to add ; charset=utf-8. Some
frameworks add it anyway; it's harmless but redundant per RFC 8259.
FAQ
What happens if I send the wrong content type?
Many strict API clients and some frameworks (like Express with express.json()) will refuse
to auto-parse the body if the header isn't application/json, leading to confusing "empty body"
bugs.
Is text/json ever correct?
No, it was never standardized. Some very old servers emit it, but new code should always send
application/json.
This article explains and expands on the community answers to the Stack Overflow question “Which JSON content type do I use?”, used under the CC BY-SA 4.0 license. Screenshot credit: Stack Exchange Inc.
No comments
Post a Comment