Search code examples
node.jsreactjsnext.jsmulter

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:

<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.