I have two applications running on my localhost, each on a different port (localhost:3000 and localhost:3002). My goal is to redirect a user from localhost:3000 to localhost:3002 while passing a JWT (JSON Web Token) between the two applications. However, my current implementation using the postMessage
method isn’t working as expected.
Here’s what I’ve tried:
Sender (localhost:3000):
const targetWindow = window.open("http://localhost:3002", "_blank");
if (targetWindow) {
targetWindow.addEventListener("load", () => {
const jwtToken = "my_jwt_token";
targetWindow.postMessage({ jwtToken }, "http://localhost:3002");
});
}
Receiver (localhost:3002):
useEffect(() => {
window.addEventListener("message", (event) => {
if (event.origin === "http://localhost:3000") {
const { jwtToken } = event.data;
}
});
}, [])
However, I’m not seeing any messages in the console when I print the "message" event. Could you please help me identify what might be causing this issue? Is there a better approach to achieving my goal of sharing a JWT between these two applications running on different ports?
Any insights or guidance would be greatly appreciated.
2
Answers
I shared the jwt token throw cockles using
universal-cookie
Sender (localhost:3000):
Receiver (localhost:3002):
Note: Dont forget to clean the cookies after extracting the jwtToken
JWT tokens are safe to publish openly, so the pretty standard way to do it is to provide a query parameter:
localhost:3002?JWT=my-jwt-token
, which later is extracted from there and validated by whatever backends thelocalhost:3002
.This is the simplest solution I can imagine without hidden unwanted side effects.