I am trying to serve static react app bundle using aws lambda only.
I have used a NodejsFunction
and applied commandHooks
during bundling to bundle a react build along with my code as shown below. I have also attached it to an API gateway as u can see.
private uiLmbda = new NodejsFunction(this, "renderer", {
entry: path.join(__dirname, "..", "handlers", "ui-handler.ts"),
handler: "handler",
bundling: {
commandHooks: {
beforeBundling(inputDir: string, outputDir: string) {
const staticAssets = path.join(__dirname, "..", "build");
const relativePath = path.relative(inputDir, staticAssets);
return [`cp -r ${relativePath} ${outputDir}`];
},
afterBundling(inputDir: string, outputDir: string) {
return [];
},
beforeInstall() {
return [];
},
},
},
});
private scanAPI = new RestApi(this, "scan-api");
private uiGatewayIntegration: LambdaIntegration = new LambdaIntegration(
this.uiLmbda
);
And in constructor i am calling this :-
this.scanAPI.root.addMethod("GET", this.uiGatewayIntegration, {});
Now,i have an index.js
as my lambda handler and a build folder with index.html
and other refered static files as shown below.
the handler code is as shown :-
import * as fs from "fs";
import * as path from "path";
export const handler = async (event: any) => {
try {
console.log(path.resolve("./build/index.html"));
return {
statusCode: 200,
headers: {
"content-type": "text/html",
},
body: fs
.readFileSync(path.join(__dirname, "build", "index.html"))
.toString("utf-8"),
isBase64Encoded: false,
};
} catch (error) {
console.log(error);
}
};
so i am able to send the html using above handler.
but not the relative files as it seems the api gateway is not aware that i wish to render subdirectories from the get method. Any help on how i can do that ? attching screenshots where u can see that main.js ( referenced through html as <script src='/task/var/build/main'><script/>
) gives 403 from api gateway.
CodePudding user response:
Okay, turns out i needed to handle this case in 2 places, one was api gateway and other was lambda handler.
I attached the lambda to serve static files using express.static
and in api gateway i enabled proxy, and it worked.