Customising JavaScript fetch()
In our previous post, we explained about how the fetch API can be used in JavaScript to make GET and POST requests. Let's look at some of the more advanced concepts of the fetch API in JavaScript.
Request Object
In our previous posts and in most scenarios, the fetch API is used as:
fetch('https://tinyfrontend.com/example/submit',{
method: 'POST',
body: data
})
You can simplify and make this code more reusable using a Request
object instead. The Request constructor has the following signature:
new Request(input: Request | string, options?: RequestInit)
-
The first argument is the resource URL. Or you can pass another Request object to make a copy and reuse it in another request.
-
The second argument is the init object where you can pass custom config parameters to modify the request.
The init object accepts the following properties:
- body
- cache
- credentials
- headers
- integrity
- keepalive
- method
- mode
- priority
- redirect
- referrer
- referrerPolicy
- signal
You might have noticed that the Request constructor accepts the same arguments as the fetch API!
Let's look at an example of how this can be useful.
const baseRequest = new Request('https://tinyfrontend.com/friends',{
headers: myHeaders,
credentials: encryptedCredentials
})
const getRequest = new Request(baseRequest, {
method: 'GET'
})
const postRequest = new Request(baseRequest, {
method: 'POST',
body: data
})
fetch(getRequest).then(...)
fetch(postRequest).then(...)
Headers Object
The fetch API also provides a Headers
interface which can be used to set and reuse headers across multiple requests. The Headers
interface allows us to set, add, remove or iterate through the headers in a particular request.
To create a Headers
object, simply call the constructor:
const customHeaders = new Headers();
Then, you can add or delete custom headers to this object and reuse it in your requests.
myHeaders.append("Authorisation", encryptedToken);
myHeaders.append("Content-Type", "application/json");
myHeaders.append("X-Custom-Header", "secret-key");
myHeaders.append("X-for-endpoint1", "value");
fetch("/api/v4/endpoint1",{
headers: customHeaders
})
myHeaders.delete("X-for-endpoint1");
fetch("/api/v4/endpoint2",{
headers: customHeaders
})