I want to use Webp format for user's uploaded images in order to reduce bandwidth usage but I'm not really sure how to it with authorisation needed.
I want to limit access and control who can see a user's images, I need to pass a token to my API. The problem is that sharing the url of the image can result in persons who do not have to credentials to see the picture if it's done like that :
<img src={`${urlApi}/images/${imageId}/${token}`}/>
I've seen how to set header for image tag but I've no idea how to do it with NextJs (*) because of the nature of build in loader which return an url and would face similar credentials problems
What could be way to do this ? Any suggestions ?
(*) Moreover, from what i've seen and the console warnings I had Next does not like to use img tag
You can do this a couple of ways and you may not need the token if the token is added based on the logged in status of a user.
Method 1: Use a custom Express server to host your application. Put the route handler for images before the nextjs handler and validate your token or validate your session before returning the image.
Method 2: put your nextjs app behind nginx or apache and proxy the /images folder to an app that validates the token (JWT signed by a private key in your nextjs app?) and proxy / to the nextjs app.
In any case add cache-control headers so that the image is not cached and may only be retrieved unless the session is valid. Note that this is a best effort since once you have released the image once you have no actual control of it.
Cache-Control: no-store, no-cache, max-age=0, must-revalidate, proxy-revalidate
Note the Next/loader is meant as a way to manipulate which public image url is supplied for a given screen size. You might use a custom loader to add the token but it doesn't have utility for this use case other than that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With