What is the correct syntax for adding the xframe header module to cra rewired? - reactjs

I'm trying to return the X-Frame-Options in my create react app (rewired) but I'm not sure of the correct syntax to use to add the function to my existing override. How do I do this properly?
module.exports = override(
fixBabelImports("react-bulma-components", {
libraryName: "react-bulma-components",
libraryDirectory: "lib/components"
}),
{devServer: function(configFunction) {
return function(proxy, allowedHost) {
const config = configFunction(proxy, allowedHost)
config.headers = {
'X-Frame-Options': 'Deny'
}
return config
}
}},
...addCompressions()
);
The front end is a CRA (rewired) non-static webapp
The backend is a node app hosted seperately
I've also tried changing the buildpack to this buildback in order to add the configuration in a static.json file, but that breaks a lot of different things, uses a different server etc.

The proper way of doing this, is by not doing it... is useless, dont waste your time. Let's remember that yow CRA Page will executed on the browser and it won't send you headers/data or anything, instead it will be send as well by Nginx/Apache/NodeJs something else.
Firefox even says the same: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Frame-Options
Note: Setting X-Frame-Options inside the element is useless! For instance, has no effect. Do not use it! X-Frame-Options works only by setting through the HTTP header, as in the examples below.
Heroku
You can configure different options for your static application by writing a static.json in the root folder of your application.
Custom Headers
Using the headers key, you can set custom response headers. It uses the same operators for pathing as Custom Routes.
{
"headers": {
"/": {
"Cache-Control": "no-store, no-cache"
},
"/assets/**": {
"Cache-Control": "public, max-age=512000"
},
"/assets/webfonts/*": {
"Access-Control-Allow-Origin": "*"
}
}
}
https://blog.heroku.com/using-http-headers-to-secure-your-site

Related

Is it possible to rewrite the route of a static .txt file in Next.js

I have a Next.js application which has a robots-staging.txt file in the root of the public folder. I'm looking to add this to the rewrites function in next.config. This is what I have
async rewrites() {
const rewriteList = [
{
source: '/robots-staging.txt',
destination: '/robots.txt',
},
];
return rewriteList;
},
My initial expectation was that when I hit localhost:3000/robots.txt this would serve the staging file, however it's not working. Am I missing something?
If I understood correctly that you want to proxy /robots.txt to /robots-staging.txt, you need to make the latter the destination and not the source.
Besides that, I've experienced the same issue, and I'm not sure if this is a bug or a feature, but I found that using absolute paths/URLs works as a workaround as relative paths seem to be interpreted as pages:
async rewrites() {
{
source: "/robots.txt",
destination:
process.env.NODE_ENV === "development"
? "http://localhost:3000/robots-staging.txt"
: "https://YOUR_URL/robots-staging.txt",
},
];
},

Adding csp-html-webpack-plugin dosnt load my react webpage

I am using the npm react-app-rewired customize-cra csp-html-webpack-plugin to give my application more security following this example https://medium.com/#nrshahri/csp-cra-324dd83fe5ff
My config-overrides.js looks like this
const { override } = require("customize-cra");
const cspHtmlWebpackPlugin = require("csp-html-webpack-plugin");
const cspConfigPolicy = {
"default-src": "'none'",
"base-uri": "'self'",
"object-src": "'none'",
"script-src": ["'self'"],
"style-src": ["'self'"]
};
function addCspHtmlWebpackPlugin(config) {
if (process.env.NODE_ENV === "production") {
config.plugins.push(new cspHtmlWebpackPlugin(cspConfigPolicy));
}
return config;
}
module.exports = {
webpack: override(addCspHtmlWebpackPlugin)
};
The problem is that when I try to enter the web page it does not load anything at all and when I check the console it shows me the following list of errors
Is there a better way to apply the security policies so that I can access the page without problems?
Thank you very much for your comments and suggestions in advance.
The CSP in your config and the directives listed in the error messages doesn't match, this could likely mean that multiple CSPs are set. As content needs to pass all CSPs, you'll first need to identify and control all of them. Check response headers and meta tags for any policies.
You will need to add the font-src directive to you CSP based on the first error message. Expand the error to see which hosts names you need to add.

https://apis.google.com/js/api.js is getting blocked by csp on my production react app

I need help. https://apis.google.com/js/api.js is getting blocked by csp on my production react app. I have added the webpack config as well.
new CspHtmlWebpackPlugin({
// 'base-uri': "'self'",
// 'object-src': "'none'",
'script-src': [
"'unsafe-inline'",
"'unsafe-eval'",
"https://apis.google.com/js/api.js",
"https://www.wiris.net/demo/plugins/app/configurationjs",
"https://as.alipayobjects.com/g/component/fastclick/1.0.6/fastclick.js",
"https://cdn.mathjax.org/mathjax/latest/MathJax.js",
],
'style-src': ["'unsafe-inline'", "'self'", "'unsafe-eval'"]
})
i am using csp-html-webpack-plugin
Suggestions to check:
1. Check if there is a Redirect
If this is getting replicated in your local environment - try to see if there is a redirect (in the chrome network tab).
For privacy reasons, in 301/302 redirects to a separate domain (that is not in the allow-list), the CSP report will contain the ORIGINAL request url, which can be very confusing.
2. Try allowing the full domain
i.e. allow https://apis.google.com instead of https://apis.google.com/js/api.js and see if it persists.
3. Extra tip
There is no need/use for 'unsafe-eval' in style-src. You can remove it.
Looks like you have miconfigured csp-html-webpack-plugin - you have to include both HtmlWebpackPlugin and CspHtmlWebpackPlugin plugins in your webpack config because last one is based on the first one:
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CspHtmlWebpackPlugin = require('csp-html-webpack-plugin');
module.exports = {
// rest of webpack config
plugins: [
new HtmlWebpackPlugin()
new CspHtmlWebpackPlugin({
// CSP config here:
enabled: true,
'script-src': [
"'unsafe-inline'",
"'unsafe-eval'",
"'self'",
"https://apis.google.com/js/api.js",
"https://www.wiris.net/demo/plugins/app/configurationjs",
"https://as.alipayobjects.com/g/component/fastclick/1.0.6/fastclick.js",
"https://cdn.mathjax.org/mathjax/latest/MathJax.js",
],
'style-src': ["'unsafe-inline'", "'self'"],
processFn: defaultProcessFn,
})
]
}
Also do check:
which CSP do you really have got in the <meta equiv="content-security-policy" content="..."> tag.
do you have any Content-Security-Policy HTTP response header in the Dev Tool because some middleware(e g. Helmet) can publish its own default CSP.
And please add to the question a CSP error message from the browser console.

Got an error Invalid src prop ('here is a link') on `next/image`, hostname "localhost" is not configured under images in your `next.config.js`

I am using the Image component from Next.js (it's a new feature of Next.js). I've tried to give the source URL:
{`${API}/user/photo/${blog.postedBy.username}`}
But it shows me this error. I also make changes in my next.config.js as
module.exports = {
images: {
domains: ['localhost'],
},
}
but nothing works for me. Please help if you know anything about this.
const src = `${API}/user/photo/${blog.postedBy.username}`;
<Image loader={() => src} src={src} width={500} height={500}/>
Here, loader is a function that generates the URLs for your image. It appends a root domain to your provided src, and generates multiple URLs to request the image at different sizes. These multiple URLs are used in the automatic srcset generation, so that visitors to your site will be served an image that is the right size for their viewport.
Edit next.config.js :
module.exports = {
reactStrictMode: true,
images: {
domains: ['example.com'],
},
}
Yes, I finally got the answer. Make loader function to load it from the destination of the image.
const myLoader=({src})=>{
return `${API}/user/photo/${blog.postedBy.username}`;
}
Use this loader function the loader attribute of an Image tag.
<Image loader={myLoader} src={`${API}/user/photo/${blog.postedBy.username}`} width={500}
height={500}/>
This works for me perfectly
I had the same issue, You need to restart your dev server, you need to do that each time you make changes on your next.config.js file.
The API string should include the port. e.g. localhost:3001
There are a whole bunch of out-of-date answers here that suggest setting the domains key in next.config.js. As of Next 12.3.0 this is no longer correct; see: https://nextjs.org/docs/messages/next-image-unconfigured-host
Instead, one should use a remotePatterns property, which is a little more complicated than the old domains:
module.exports = {
images: {
remotePatterns: [
{
protocol: 'https',
hostname: 'example.com',
port: '',
pathname: '/account123/**',
},
],
},
}
Inside next.config.js file.
Add Image src domain name:
const nextConfig = {
reactStrictMode: true,
images : {
domains : ['sangw.in', 'localhost', 'picsum.photos'] // <== Domain name
}
}
module.exports = nextConfig
Adding 'localhost' in the domains array will fix the issue,
Unfortunately nextJS didn't refresh the server automatically after configuration file(next.config.js) change.
You have to restart the server manually to reflect the changes.
You can also try by set reactStrictMode value reactStrictMode: true,
here is the full export object
module.exports = {
reactStrictMode: true,
images: {
domains: [
"localhost",
process.env.WORDPRESS_API_URL.match(/(http(?:s)?:\/\/)(.*)/)[2], // Valid WP Image domain.
"2.gravatar.com",
"0.gravatar.com",
"secure.gravatar.com",
],
},
};
First of all add and restart the dev server.
domains: ['localhost']
And be sure to return the image link with http(s) protocole
image link with localhost:port/... is wrong , return as http://localhost/... ( or with https )
I've faced the same issue, and my domains were correct. Deleting .next and node_modules folders, and running yarn/npm install fixed the issue.
For me, in next.config.js,
/** #type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
images: {
domains: [ "abc.def.org", ]
},
}
module.exports = nextConfig
and then in my Image tag
<Image
unoptimized // for image caching, else error
src={profile.picture}
alt={profile.picture || "IMG"}
width={60}
height={60}
/>

How to proxy with Gatsby and custom Webpack config (netlify-lambda)

I'm using Gatsby with netlify-lambda which creates a server for functions on the 9000 ports:
http://localhost:9000/myFunctionName
In production the address of the functions is:
/.netlify/functions/myFunctionName
So I would like to have a dev mode proxy that serves http://localhost:9000/ when I call /.netlify/functions.
My custom Webpack config in gatsby-node.js:
exports.modifyWebpackConfig = ({ config, stage }) => {
if (stage === 'develop') {
config.merge({
devServer: {
proxy: {
'/.netlify/functions': {
target: 'http://localhost:9000',
pathRewrite: {
'^/\\.netlify/functions': ''
}
}
}
}
})
}
}
Does not work.
I tried this too https://www.gatsbyjs.org/docs/api-proxy/#api-proxy but I need to rewrite the url and not just prefix.
What's the best way to use netlify-lambda with Gatsby ?
Thanks
Update: Gatsby now does support Express middleware, in this merged PR. This will not support the Webpack Dev Server proxy configuration, but will allow using ordinary Express proxy middleware.
To use with netlify-lambda just add this to your gatsby-config.js :
const proxy = require("http-proxy-middleware")
module.exports = {
developMiddleware: app => {
app.use(
"/.netlify/functions/",
proxy({
target: "http://localhost:9000",
pathRewrite: {
"/.netlify/functions/": "",
}
})
)
}
}
https://www.gatsbyjs.org/docs/api-proxy/#advanced-proxying
Unfortunately, the Gatsby development proxy configuration is not at all extensible. Since Gatsby does not use the webpack dev server, its proxy options are not available. See https://github.com/gatsbyjs/gatsby/issues/2869#issuecomment-378935446
I achieve this use case by putting an nginx proxy in front of both my Gatsby development server and the netlify-lambda server. This is a very simplified version of the proxy server config (trailing slash is important):
server {
listen 8001;
location /.netlify/functions {
proxy_pass http://0.0.0.0:9000/;
}
location / {
proxy_pass http://0.0.0.0:8000;
}
}
I'm using an nginx proxy anyhow, so that's not an undesirable amount of extra dev setup, but it would certainly be better if Gatsby supported this common case.

Resources