Is this the way to make a query?
Unanswered
JChicano posted this in #help-forum
JChicanoOP
Hello, I am making queries on my page in the following way, and I would like to know if I am doing it correctly or if it is vulnerable to security risks. If it is, I’d like to understand how to prevent it.
I am retrieving the user ID from the session (stored by NextAuth) and passing it to a fetch function, which sends a request to the API with the user ID to fetch the desired data. The problem is that it might be possible to modify the request URL and replace the user ID with another one, potentially accessing private information that shouldn’t be accessible.
Is this possible? And if so, what is the best way to fix it? Thanks!
I am retrieving the user ID from the session (stored by NextAuth) and passing it to a fetch function, which sends a request to the API with the user ID to fetch the desired data. The problem is that it might be possible to modify the request URL and replace the user ID with another one, potentially accessing private information that shouldn’t be accessible.
Is this possible? And if so, what is the best way to fix it? Thanks!
// Endpoint to get the user data
const session = await getServerSession(authOptions);
//Getting the info of the user
const userDataPromise = fetchUserData(session.user.id);
export async function fetchUserData(userId: string) {
try {
const response = await fetch(
`${process.env.NEXT_PUBLIC_BASE_URL}/api/selectInfoUser?user=${userId}`,
{
cache: "force-cache",
next: { tags: ["user-data"], revalidate: 3600 },
}
);
if (!response.ok) {
console.error("Error fetching user data:", response);
return null;
}
return await response.json();
} catch (error) {
console.error("Fetch user data failed:", error);
return null;
}
}
export async function GET(req: NextRequest) {
// Get the user id from the request URL
const { searchParams } = new URL(req.url);
const userId = searchParams.get("user") || "";
// Select the user data from the database
const user = await selectUser(userId);
// Return the user data
return NextResponse.json(user);
}