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.
I shared the jwt token throw cockles using universal-cookie
Sender (localhost:3000):
const jwtToken = 'your_jwt_token_here';
const cookies = new Cookies();
cookies.set('jwtToken', jwtToken, { path: '/' });
Receiver (localhost:3002):
const cookies = new Cookies();
const jwtToken = cookies.get('jwtToken')
Note: Dont forget to clean the cookies after extracting the jwtToken