NextJS api authentication with 3rd party API

Hello ! We currently have a NextJS app that uses its API routes to call an external API and retrieve data that way. So essentially such files might look like this.
import env from "@env/server.mjs";
import axios from "axios";
import { NextApiRequest, NextApiResponse } from "next";

export default async function building(
req: NextApiRequest,
res: NextApiResponse,
) {
const { id } = req.query;
const { assetUrl } = env;
const baseUrl = `${assetUrl}/building`;
const url = id !== undefined ? `${baseUrl}/${id}` : baseUrl;
const token = req.headers["access-token"] as string;

try {
const response = await axios.get(url, {
headers: {
"Access-Token": token,
"Content-Type": "application/json",
"Cache-Control": "no-cache",
},
});
res.status(200).json(response.data);
} catch (err) {
if (axios.isAxiosError(err)) {
res.status(err.response!.status).json(err.response!.data);
}
}
}
import env from "@env/server.mjs";
import axios from "axios";
import { NextApiRequest, NextApiResponse } from "next";

export default async function building(
req: NextApiRequest,
res: NextApiResponse,
) {
const { id } = req.query;
const { assetUrl } = env;
const baseUrl = `${assetUrl}/building`;
const url = id !== undefined ? `${baseUrl}/${id}` : baseUrl;
const token = req.headers["access-token"] as string;

try {
const response = await axios.get(url, {
headers: {
"Access-Token": token,
"Content-Type": "application/json",
"Cache-Control": "no-cache",
},
});
res.status(200).json(response.data);
} catch (err) {
if (axios.isAxiosError(err)) {
res.status(err.response!.status).json(err.response!.data);
}
}
}
Probably not the best code, but what I'm wondering is about the token we have for authentication, is there a way to persist that token or use (maybe) a middleware next provides so we don't pass it through cookies ?
0 Replies
No replies yetBe the first to reply to this messageJoin
Want results from more Discord servers?
Add your server