I am creating an api call in a Nextjs (with Supabase) application which need to be sercured. For my application a user should be logged which is enforced by the middleware and the await supabase.auth.getUser()
call.
However, I would like to call the API from an external service or Edge function. A solution would be to make an exception for the /api path to not check for the logged user, but that would not be safe.
So I created some code to check whether the Service role key of Supabase is passed with the api call:
const isApiRequest = request.nextUrl.pathname.startsWith("/api");
// If the request is for /api, enforce authentication header
if (isApiRequest) {
const authHeader = request.headers.get("authorization");
if (authHeader?.startsWith("Bearer ")) {
const token = authHeader.replace("Bearer ", "").trim();
const { data, error } = await supabase.auth.getUser(token);
if (!data.user || error) {
return new NextResponse("Unauthorized", { status: 401 });
}
} else {
return new NextResponse("Unauthorized", { status: 401 });
}
}
However, this code does not work. The getUser(token) does not work like this. How can I solve this?