JSONP
JSONP ("JSON with Padding") is a technique from the late 2000s for loading data from another domain before browsers had a safe, official way to do so. You will still meet it in old code and old API documentation, so it's worth understanding — mainly so you can recognise it and replace it.
Note: Don't use JSONP in new projects. Use
fetch()with CORS instead. This lesson explains why.
The problem JSONP solved
Browsers follow the same-origin policy: JavaScript on https://mysite.example may not read responses from https://api.other.example. Back then, there was no way for the API to say "it's fine, you may read this".
But one thing was always allowed: a <script src="..."> tag can load a script from any domain. JSONP exploits that.
How it works
- Your page defines a global function, the callback:
function showWeather(data) {
console.log(data.city + ": " + data.temp + "°C");
}- You add a script tag that points to the API and passes the callback's name in the URL:
<script src="https://api.other.example/weather?city=Hue&callback=showWeather"></script>- Instead of plain JSON, the server returns JavaScript: the JSON data wrapped ("padded") in a call to your function:
showWeather({"city": "Hue", "temp": 29});- The browser runs that script, which calls
showWeatherwith the data.
Simulating the mechanism
We can't load a cross-domain script here, but we can show what the server builds and what the browser effectively does with it. Notice that the client ends up executing code supplied by the server:
// --- server side: wrap JSON in a function call ---
function jsonpResponse(callbackName, data) {
return `${callbackName}(${JSON.stringify(data)});`;
}
const body = jsonpResponse("showWeather", { city: "Hue", temp: 29 });
console.log("Server sends:", body);
// --- client side: the browser would *run* this text as a script ---
function showWeather(data) {
console.log(`${data.city}: ${data.temp}°C`);
}
const run = new Function("showWeather", body);
run(showWeather);Server sends: showWeather({"city":"Hue","temp":29});
Hue: 29°C
Why JSONP is a bad idea today
| Problem | Explanation |
|---|---|
| Runs arbitrary code | The response is a script with full access to your page. A hacked or malicious API can steal cookies, tokens or user input. |
| GET only | A script tag can't send POST/PUT/DELETE or a JSON body. |
| Poor error handling | If the request fails or the server returns garbage, there's no status code to inspect — at best a vague onerror. |
| Data leaks (CSRF-style) | Any website can include your JSONP URL in a script tag. If the API uses the visitor's cookies, a malicious site can read their private data. |
| Callback injection | Servers must validate the callback name, or attackers can inject code through it. |
| Global functions | Every request needs a callback in the global scope. |
A server that still offers JSONP should at least restrict the callback name to safe characters:
function safeCallback(name) {
return /^[A-Za-z_$][\w$]*(\.[A-Za-z_$][\w$]*)*$/.test(name);
}
for (const name of ["showWeather", "app.handlers.weather", "steal(1);x", "x</script>"]) {
console.log(name.padEnd(22), safeCallback(name) ? "allowed" : "rejected");
}showWeather allowed
app.handlers.weather allowed
steal(1);x rejected
x</script> rejected
The modern replacement: CORS + fetch
Today, the API server adds a CORS header to say which sites may read its responses:
HTTP/1.1 200 OK
Content-Type: application/json
Access-Control-Allow-Origin: https://mysite.example
{"city": "Hue", "temp": 29}And the client uses ordinary fetch(). The response is data, parsed by JSON.parse — never executed:
const response = await fetch("https://api.other.example/weather?city=Hue");
const data = await response.json();
console.log(`${data.city}: ${data.temp}°C`);| JSONP | CORS + fetch | |
|---|---|---|
| Response type | JavaScript code | JSON data |
| HTTP methods | GET only | All |
| Error handling | Almost none | Status codes, exceptions |
| Security | Executes remote code | Data only; server controls access |
| Browser support | Every browser | Every modern browser |
Recognising JSONP in old code
Look for:
- URLs with
callback=,jsonp=orcb=parameters. - jQuery calls like
$.ajax({ dataType: "jsonp" })or$.getJSON(url + "?callback=?"). - Responses served as
application/javascriptthat start with a function name and(.
When you find it, check whether the API supports CORS (most do now) and switch to fetch().
Test yourself
What does a JSONP response contain?
- Plain JSON
- XML
- JavaScript that calls a function with the data
- A binary file
Which HTML element does JSONP rely on?
- <iframe>
- <link>
- <script>
- <object>
What should replace JSONP in new code?
- eval()
- fetch() with CORS
- A hidden iframe
- Flash