I am using react js for Frontend and strapi as backend, so i wanna know how i can set up http cookie. I am working on e-commerce website, my strapi version 4.13.7
This topic has been created from a Discord post (1259072146387505152) to give it more visibility.
It will be on Read-Only mode here.
Join the conversation on Discord
I’m using a server action on my next.js project which sets the jwt cookie on sign_in
* Sets the JWT cookie with the appropriate expiration time.
* @param jwt - The JSON Web Token to be stored in the cookie.
*/
function setJwtCookie(jwt: string): void {
let exp: number | null = null;
try {
const payload = JSON.parse(
Buffer.from(jwt.split(".")[1], "base64").toString()
);
exp = payload.exp || null;
} catch (error) {
exp = null;
}
const defaultExpirationTime = 24 * 60 * 60 * 1000; // 24 hours in milliseconds
const expirationTime = exp ? exp * 1000 : Date.now() + defaultExpirationTime;
const expires = new Date(expirationTime);
cookies().set("jwt", jwt, {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "strict",
path: "/",
expires,
});
}
* Signs in the user with the provided credentials.
* Sets the JWT cookie and redirects to the dashboard on success.
* @param _prevState - Previous state, unused.
* @param formData - Form data containing 'identifier' and 'password'.
* @returns A message indicating the failure of the operation, or redirects to the dashboard on success.
*/
export async function sign_in(
_prevState: unknown,
formData: FormData
): Promise<FormMessage> {
try {
const identifier = formData.get("identifier") as string;
const password = formData.get("password") as string;
const response = await fetch(AUTH_URL, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ identifier, password }),
});
const { jwt, error } = await response.json();
await new Promise((resolve) => setTimeout(resolve, 1500));
if (error) {
if (error.status === 400) {
return { message: "Invalid username or password" };
}
return { message: error.message || "Server Error", type: "error" };
}
if (jwt) {
setJwtCookie(jwt);
}
} catch (error) {
return { message: "Server Error" };
}
redirect("/dashboard");
}
thanks man bbut i am using react js
Next.js is a react framework, you can do the same thing in react.
But somehow i managed to store http cookie the other way
But isssue now is fetching it, i m using a route called protected which uses policy isAuthenicated with check with jwt token if user exists or not
But the problem is i m getting 403 error
I am not able set the policy propery