Like the title says, when I make a request to an external API from my client side component, I get a 403, but if I make it from a server component, it works just fine.
The reason I need to make the call from client side is because the user makes a selection and the request made depends on the selection, so useState() is used to manage the selection. The user selects a sector, and then the call to get industries by sector id is made.
The relevant client component code:
const { data: session } = useSession();
const [sector, setSector] = useState<Sector | null>(null);
const [industries, setIndustries] = useState<Industry[]>([]);
const [industry, setIndustry] = useState<Industry | null>(null);
const handleSectorSelection = (event: React.ChangeEvent<{}>, value: Sector | null) => {
setSector(value);
};
const handleIndustrySelection = (event: React.ChangeEvent<{}>, value: Industry | null) => {
setIndustry(value);
};
useEffect(() => {
const getIndustries = async (sectorId: number) => {
const response = await getIndustriesBySectorId(sectorId, session?.jwt);
setIndustries(response.result as Industry[]);
};
if (sector && sector.id != null) {
getIndustries(sector.id);
} else {
setIndustries([]);
}
}, [sector, session?.jwt]);
return (...
<SectorSelectDropdown
options={sectors}
onChange={handleSectorSelection}
renderInput={(params) => <TextField {...params} label="Search" variant="outlined" />}
/>
{industries && industries.length > 0 ? (
<IndustrySelectDropdown
options={industries}
onChange={handleIndustrySelection}
renderInput={(params) => <TextField {...params} label="Search" variant="outlined" />}
/>
) : null} ...)
The sectors property is passed down from the parent component
The API call:
export async function getIndustriesBySectorId(sectorId: number, jwt?: string) {
let result = null,
error = null;
if (!jwt) {
throw new Error("Session JWT token not found.");
}
try {
console.log(jwt);
result = await fetch(`${process.env.NEXT_PUBLIC_POSITIONS_SERVICE_URL!}/industries/sector/${sectorId}`, {
method: "GET",
headers: {
"Content-Type": "application/json",
Cookie: `Authentication=${jwt}`,
},
credentials: "include",
});
if (!result.ok) {
throw new Error(`Failed to fetch industry: ${result.statusText}`);
}
const data: Industry[] = await result.json();
return { result: data, error: null };
} catch (e) {
error = e;
return { result: {}, error: error };
}
}
If I make the call from a server component, I would change things up within this file and get the session data directly (instead of passing them in) like this:
export async function getPositions() {
const session = await getServerSession(authOptions);
let result = null,
error = null;
if (!session?.jwt) {
throw new Error("Session JWT token not found.");
}...
So, is there a way to accomplish what I need to do with the current setup? Or is there a way to make my current client side component a server side component? I am new to NextJS, so perhaps my entire setup is wrong?