I’m currently working on a Next.js project where I need to handle authentication and API requests using Axios. I’m a bit confused about whether I’m doing it right, especially when it comes to setting up Axios and handling cookies. Here’s the setup I have so far:
Axios Setup
I created a singleton class for Axios to manage API requests:
import AsyncStorage from "@react-native-async-storage/async-storage";
import axios, { AxiosInstance } from "axios";
export default class ExampleApi {
private apiInstance: AxiosInstance;
private static instance: ExampleApi;
public _accessToken: string | undefined;
private constructor(atoken?: string) {
this.apiInstance = axios.create({
baseURL: "http://localhost:4040/api",
headers: {
"Content-Type": "application/json",
},
timeout: 3000,
withCredentials: true,
});
}
public static getInstance(accessToken?: string): ExampleApi {
if (!ExampleApi.instance) {
ExampleApi.instance = new ExampleApi(accessToken);
}
return ExampleApi.instance;
}
public async post(api: string, body: any) {
try {
const res = await this.apiInstance.post(api, body);
return {
data: res.data,
headers: res.headers,
};
} catch (error) {
return error;
}
}
public async get(api: string, body: any) {
const res = await this.apiInstance.get(api, body);
return {
data: res.data,
headers: res.headers,
};
}
}
Next.js API Routes
Then, I use this ExampleApi class in my Next.js API routes like this:
GET EXAMPLE
import ExampleApi from "@service/app/services/exampleApi";
import { NextRequest, NextResponse } from "next/server";
export async function GET(req: NextRequest) {
const cookies = req.headers.get('cookie');
const res: any = await ExampleApi.getInstance().get("/account/info", {
headers: { "Cookie": cookies }
});
const response = NextResponse.json(res.data.data);
return response;
}
POST EXAMPLE
import ExampleApi from "@service/app/services/exampleApi";
import { NextResponse } from "next/server";
export async function POST(request: Request) {
const reqres = await request.json();
const res: any = await ExampleApi.getInstance().post(
"/account/login",
{
email: reqres.email,
password: reqres.password,
}
);
const response = NextResponse.json(res);
const setCookieHeader = res.headers["set-cookie"];
if (setCookieHeader) {
setCookieHeader.forEach((cookie: string) => {
response.headers.append("Set-Cookie", cookie);
});
}
return response;
}
Am I handling cookies correctly in the GET and POST routes, especially with setting Set-Cookie headers in the response?
Is my approach to managing access tokens correct? How can I improve this, especially when storing and passing tokens in the headers?