Below is my signin function, whenthe signin is successfull i am setting cookie.
export const signIn = async (payload) => {
try {
const res = await axios({
method: "post",
url: "http://localhost:8000/api/v1/users/signin",
data: payload,
});
console.log("--Signin response--", res.data);
const cookieData = { token: res.data.token, user: res.data.data };
// Serialize the cookie with necessary options
const cookieOptions = {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
maxAge: 60 * 60 * 24 * 7, // 1 week
path: "/",
};
// Set the cookie using cookies module
cookies().set("onlyjs_cookie", JSON.stringify(cookieData), cookieOptions);
return res.data;
} catch (err) {
console.log("--Signin error--", err.response.data.message);
throw new Error(err.response.data.message);
}
};
Whenever i make external api calls, i am sending the beare token with request then the backend will check for the verification of token and if expired throws 401 error,
Below is my apiRequest reusable function
"use server";
import axios from "axios";
import { cookies } from "next/headers";
const appAxiosInstance = axios.create({
baseURL: "http://localhost:8000/api/v1/",
withCredentials: true,
});
export async function ApiRequest(endUrl, method = "get", config = {}) {
let errorMsg = null;
const defaultConfig = {
url: endUrl,
method: method,
baseURL: "http://localhost:8000/api/v1/",
};
const finalConfig = { ...defaultConfig, ...config };
try {
const cookie = cookies().get("onlyjs_cookie")?.value;
if (cookie) {
const parsedCookie = JSON.parse(cookie);
if (parsedCookie?.token) {
console.log("--Cookie token--", parsedCookie?.token);
finalConfig.headers = {
...finalConfig.headers,
authorization: `Bearer ${parsedCookie.token}`,
};
}
}
const response = await appAxiosInstance(finalConfig);
return response.data;
} catch (error) {
if (error?.response) {
if (error.response.status === 401) {
cookies().delete("onlyjs_cookie");
}
} else if (error?.request) {
errorMsg = "Cannot connect to the server";
} else {
errorMsg = "Unexpected error occurred!";
}
throw new Error(errorMsg || "Something went wrong");
}
}
I am calling apiRequest from serve action below
export const getAllTutorials = async () => {
try {
await ApiRequest("tutorials");
} catch (err) {
// console.log("--Tutorials error--", err);
}
};
If the 401 error comes in apiRequest then i simply want to delete the cookie which i previously set during signin and also want to redirect the user to login.
How can i achieve that?
The error i am getting is
headers can only be set using server actions or api route handlers
I have tried both approaches but no luck.
Please help me.