Skip to content

Commit

Permalink
send cookie in headers
Browse files Browse the repository at this point in the history
  • Loading branch information
mahmodghnaj committed Nov 4, 2023
1 parent 6772ce0 commit 8097e1f
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 5 deletions.
14 changes: 10 additions & 4 deletions lib/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,16 @@ async function getInfoSession() {
const response = await fetch(`${url}/auth/info-session`, {
method: "post",
headers: {
Cookie: cookies()
.getAll()
.map(({ name, value }) => `${name}=${value}`)
.join("; "),
// If the front-end and back-end are on the same domain,
// there's no need to store the refresh token in cookies,
// as the back-end will send the refresh token in a cookie.
// This function is used for different domain scenarios.
///////////////////////////////////////
// Cookie: cookies()
// .getAll()
// .map(({ name, value }) => `${name}=${value}`)
// .join("; "),
refresh: cookies().get("refresh")?.value || "",
},
});
const res = await response.json();
Expand Down
9 changes: 8 additions & 1 deletion lib/axios/interceptors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,13 @@ export function sleep(ms: number) {
// as the back-end will send the refresh token in a cookie.
// This function is used for different domain scenarios.
export const setRefreshToken = (value: string) => {
Cookies.set("refreshToken", value, { expires: 365 });
Cookies.set("refresh", value, { expires: 365 });
};
const injectRefreshToken = (config: InternalAxiosRequestConfig) => {
const re = Cookies.get("refresh");
const isInject = ["/auth/info-session", "/auth/refresh"];
if (re && config.url && isInject.includes(config.url))
config.headers.set("refresh", re);
};

import {
Expand All @@ -29,6 +35,7 @@ export interface ConsoleError {
export const requestInterceptor = async (
config: InternalAxiosRequestConfig
): Promise<InternalAxiosRequestConfig> => {
injectRefreshToken(config);
const token = useStore.getState().auth.token;
if (token) {
config.headers.set("Authorization", `Bearer ${token}`);
Expand Down

0 comments on commit 8097e1f

Please sign in to comment.