Home > database >  Show protected image from API to Next.js client in an img tag
Show protected image from API to Next.js client in an img tag

Time:04-13

I am trying to show a protected image from my Node.js backend assets folder.

It has a middleware that checks whether the user is logged in and has permission to access the file.

In the client side I want to display the image in an img tag:

<img src"localhost:5000/uploads/image.png" />

Is there a way to intercept this request to pass the user's token so he will be able to access the image?

Thanks

CodePudding user response:

You can implement this in one of these ways:

  1. Use Cookies for authentication
  2. Use token as a query parameter for the image URL

Cookies

When login you can send cookies to the browser and use middleware to validate if the user has permission to view the image.

router.use("/uploads", function(req, res, next) {
    // Check if the user is loged in
    if (req.isAuthenticated()) {
    next();
    } else {
        res.status(401).send("You are not authorized to view this page");
    }
});

// Static files
router.use("/uploads", express.static(path.join(__dirname, 'public')));

Token

similarly you can use a token like this

<img src="localhost:5000/uploads/image.png?token=xxxxxxxxxxxxxx" />

router.use("/uploads", function(req, res, next) {
    // Check if the user is loged in
    if (req.query.token && checkToken(req.query.token)) {
        next();
    } else {
        res.status(401).send("You are not authorized to view this page");
    }
});

// Static files
router.use("/uploads", express.static(path.join(__dirname, 'public')));

Note: This code uses express as an example. You'll have to implement this middleware in whatever Library you are usng.

CodePudding user response:

using blob you can delay bind the image downloaded from backend API to < img > tag

<img id="image"/>

response from API is passed to below function

function response(e) {
   var urlCreator = window.URL || window.webkitURL;
   var imageUrl = urlCreator.createObjectURL(this.response);
   document.querySelector("#image").src = imageUrl;
}
  • Related