23

I have some static assets that I want to serve inside iframes of several desktop / mobile web clients.

Now, how do I whitelist a specific set of origins to be allowed setting of X-Frame-Options headers so that the resource can be embedded as iframes inside different desktop / mobile web clients. and for all other origins denies the access to this resource.

With a little digging I started off with -

const app = express();

var allowCrossDomain = function (req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
    res.header('Access-Control-Allow-Headers', 'Content-Type, X-Requested-With, Authorization');
    if (req.method === "OPTIONS") res.send(200);
    else next();
}
app.use(allowCrossDomain);

Now here how do I set the X-Frame-Options header with the whitelisted origin values here -

3 Answers 3

20

You should import helmet and use frameguard to get some origins whitelisted. More on this topic: MDN X-FRAME-OPTIONS Best Practice Security

2
  • 2
    According to MDN 'x-Frame-Options' is obsolete in modern browsers, and it's better to avoid using it: helmetjs.github.io/docs/frameguard (read 'allow from' section)
    – Ebrahim
    Jul 22, 2020 at 9:01
  • 1
    I downvoted this since it's overkill to import an entire library to accomplish something so trivial (despite what Express recommends)
    – Steven
    Jun 20, 2022 at 15:29
11

all you need is helmet

npm install helmet --save 

const express = require('express')
const helmet = require('helmet')

const app = express()

app.use(helmet.frameguard())
2
  • 2
    if I add only app.use(helmet()) is it ok?? am using helmet version 3.21.3 Mar 13, 2020 at 5:37
  • 1
    @BijaySingh yes that should do..according to the doc helmetjs.github.io/docs
    – Edwin O.
    Mar 13, 2020 at 9:31
0

To address Steven's concern, you can install the frameguard package only

   npm install helmet --save 

   const frameguard = require("frameguard");

   // Don't allow me to be in ANY frames:
   app.use(frameguard({ action: "deny" }));

   // Only let me be framed by people of the same origin:
    app.use(frameguard({ action: "sameorigin" }));
    app.use(frameguard()); // defaults to sameorigin

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.