Explain Codes LogoExplain Codes Logo

Authorization header in img src link

javascript
fetch-api
service-worker
base64-encoding
Nikita BarsukovbyNikita Barsukov·Jan 30, 2025
TLDR

To provide an Authorization header when displaying an image, you can leverage server-side processing via a proxy. With Node.js and Express, fetch the image using your credentials, then pipe it back to the client:

app.get('/image', async (req, res) => { const imgResponse = await fetch('IMAGE_URL', { headers: { 'Authorization': 'Bearer TOKEN' } }); // Your image URL secret agent fetches in action! res.type(imgResponse.headers.get('content-type')); imgResponse.body.pipe(res); // Just piping the image data, nothing to see here! });

In the HTML file, the <img> tag's src attribute refers to your proxy route:

<img src="/image" alt="Secured Image"/>

Make sure to replace 'IMAGE_URL' with the specific URL for your image and 'TOKEN' with your access token. This approach lets your server play the middleman role, delivering the image to the client while safeguarding your secrets!

Using JavaScript for your secret mission

When you need more control on the client side or want to avoid a server-side proxy, consider these alternative strategies:

Fetch API: Your secret agent for image retrieval

The fetch API allows you to request images with custom headers:

fetch('IMAGE_URL', { headers: { 'Authorization': 'Bearer TOKEN' // Here's the secret handshake! } }) .then(response => response.blob()) // Transforming top secret data! .then(blob => { const imageUrl = URL.createObjectURL(blob); // Memory wiped clean! document.getElementById('image').src = imageUrl; // Mission accomplished! });

The blob , a mystery in itself, gets converted into a URL readable by the <img> tag, leaving no tracks!

Service Worker: Interceptor of requests

Being the ninja it is, a Service Worker can intercept network requests and modify them:

self.addEventListener('fetch', event => { if (event.request.url.endsWith('/image')) { const newHeaders = new Headers(event.request.headers); newHeaders.append('Authorization', 'Bearer TOKEN'); // Disguised as a normal header! const modRequest = new Request(event.request, { headers: newHeaders }); event.respondWith(fetch(modRequest)); // Intercept, conceal, continue! } });

A Service Worker empowers you to control how resources are fetched, but remember, with great power comes great responsibility!

Moonlighting images with data URI

Small-sized images can go undercover as base64-encoded data URIs:

fetch('IMAGE_URL', { headers: { 'Authorization': 'Bearer TOKEN' // Permit? Check! } }) .then(response => response.arrayBuffer()) // Transforming the image into an engima! .then(buffer => { const base64Flag = 'data:image/jpeg;base64,'; const imageStr = arrayBufferToBase64(buffer); // Converting the enigma to base64! document.getElementById('image').src = base64Flag + imageStr; // Uploading undercover image! });

Decoding potentially large files in this manner can impact performance and security, so weigh your needs with caution.

JWTs: The secret agents of encoding

JSON Web Tokens (JWT) carry sensitive information and should be securely managed. Opt for HttpOnly cookies or query parameters paired with short-lived nonces:

// Server side: generating a nonce for the secret mission app.get('/generate-nonce', (req, res) => { const nonce = createNonce(req.user); // Got your secret code, agent! res.json({ nonce }); }); // Client side: nonce-secured image retrieval fetch('/path-to-image?nonce=' + nonce).then(response => /* ... */); // Securing the goods with secret codes!

Ensuring the nonce's validity for each image request protects your security while dealing with these secret agents.

Other secret tactics to consider

Appreciating the range of tools at your disposal is the first step to mastering the inclusion of Authorization headers in your image fetching operations.

Utilizing axios over fetch

Axios, a promise-based HTTP client, could be a more reliable fetch alternative:

axios.get('IMAGE_URL', { responseType: 'arraybuffer', headers: { 'Authorization': `Bearer ${TOKEN}` // The secret handshake in action! } }) .then(response => { const base64 = Buffer.from(response.data, 'binary').toString('base64'); document.getElementById('image').src = `data:image/jpg;base64,${base64}`; // Swapping the disguise for a party mask! });

Axios assures finer request control, robust error handling, and a dash of class to your HTTP requests.

Middleware for the cloak and dagger

On the server, middleware can take care of converting credentials from cookies into Authorization headers. Consider Express middleware to form the backbone of your server-side operations.

Enrich your toolkit

For the code enthusiasts, detailed tutorials and resources on fetch API, Service Workers, Base64 images, and safe handling of JWTs and nonces can be invaluable!