Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading