I have a React (Vite) app that I'm hosting from S3/CloudFront. It gets there via AWS CDK.
In the CDK (CloudFormation) process, I'm generating a deploy time JSON file `config.json) that I'm also putting into the same S3 bucket as the React app. See image below for what my bucket ends up looking like:
What I would like to do is access the values in this config.json
during runtime in my React app. In my running React App from CloudFront, It doesn't seem to be aware about the config.json
file though:
To be clear, what I would like to do is do something like the following:
// App.tsx
import * as config from "./config.json"
fetch(config.url, ....)
Note: Cloudfront does have privelages for all files in this bucket:
siteBucket.addToResourcePolicy(
new iam.PolicyStatement({
actions: ["s3:GetObject"],
resources: [siteBucket.arnForObjects("*")],
principals: [
new iam.CanonicalUserPrincipal(
cloudfrontOAI.cloudFrontOriginAccessIdentityS3CanonicalUserId
),
],
})
);
new CfnOutput(this, "Bucket", { value: siteBucket.bucketName });
CodePudding user response:
I found this article which outlined a similar pattern.
By fetching the file on mount, I can read the appropriate config that's generated at deploy time at the top level of the React app:
// App.tsx
function App() {
const [data, setData] = useState([]);
useEffect(() => {
fetch("/config.json")
.then(function (res) {
return res.json();
})
.then(function (data) {
setData(data);
})
.catch(function (err) {
console.log(err, " error");
});
}, []);
return (
<div>{JSON.stringify(data, null, 2)</div>
);
}