Locally API Route Works, On Vercel 405
Answered
Acorn-plum gall posted this in #help-forum
Acorn-plum gallOP
Hey, I've been caught on this for the last two days.
I have an api route that takes in an image for uploading to my supabase storage bucket. When run on localhost everything works perfectly, but when the API route gets hit on the vercel host I get an error 405 (Method Not Found).
I believe this may be an issue with Sharp + NextJS working together as I had to downgrade sharp already to avoid another bug (https://github.com/orgs/vercel/discussions/5449#discussioncomment-8118778).
Here is my api route:
I have an api route that takes in an image for uploading to my supabase storage bucket. When run on localhost everything works perfectly, but when the API route gets hit on the vercel host I get an error 405 (Method Not Found).
I believe this may be an issue with Sharp + NextJS working together as I had to downgrade sharp already to avoid another bug (https://github.com/orgs/vercel/discussions/5449#discussioncomment-8118778).
Here is my api route:
import { NextRequest, NextResponse } from "next/server";
import { cookies } from "next/headers";
import { createServerClient } from "@supabase/ssr";
import { getUser } from "@/lib/utils";
import sharp from "sharp";
export async function POST(request: NextRequest) {
// Check if environment variables are set
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL;
const supabaseAnonKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY;
if (!supabaseUrl || !supabaseAnonKey) {
return NextResponse.json(
{ error: "Server configuration error." },
{ status: 500 }
);
}
const cookieStore = cookies();
const supabase = createServerClient(supabaseUrl, supabaseAnonKey, {
cookies: {
get(name: string) {
return cookieStore.get(name)?.value;
},
},
});
try {
const formData = await request.formData();
const file = formData.get("file");
const fileName = formData.get("fileName");
if (!file || typeof file !== "object" || !(file instanceof Blob)) {
return NextResponse.json(
{ error: "Invalid file provided." },
{ status: 400 }
);
}
if (!fileName || typeof fileName !== "string") {
return NextResponse.json(
{ error: "Invalid file name provided." },
{ status: 400 }
);
}
const reformattedFileName = fileName
.replace(/\s/g, "_")
.replace(/[^\w.-]/g, "");
const convertedImage = await sharp(Buffer.from(await file.arrayBuffer()))
.resize(750, 750, { fit: "cover", position: "center" })
.webp()
.toBuffer();
const user = await getUser(cookieStore);
if (!user) {
return NextResponse.json(
{ error: "User authentication failed." },
{ status: 401 }
);
}
const { data, error: selectError } = await supabase
.from("restaurants")
.select("id")
.eq("client", user.id)
.single();
if (selectError) {
throw selectError;
}
const { error: uploadError } = await supabase.storage
.from("f3ast-client-menu-assets")
.upload(`${data.id}/${reformattedFileName}.webp`, convertedImage, {
contentType: "image/webp",
});
if (uploadError) {
throw uploadError;
}
return NextResponse.json({ Message: "Success", status: 201 });
} catch (error: any) {
console.error("Error occurred: ", error);
return NextResponse.json({
Message: "Failed",
status: 500,
error: error.message,
});
}
}Answered by Toyger
so it's then sharp issue, here https://github.com/lovell/sharp/issues/3870 people reccomend to downgrade to
0.32.613 Replies
Toyger
405 is either you use wrong url either your request to url isn't POST.
Acorn-plum gallOP
It works locally, just not on Vercel, why would the url change?
@Acorn-plum gall It works locally, just not on Vercel, why would the url change?
Toyger
because locally you have
http://localhost:3000 and on vercel it is some real domain nameAcorn-plum gallOP
With all due respect no where in my code references localhost. only this API route does not work.
@Acorn-plum gall With all due respect no where in my code references localhost. only this API route does not work.
Toyger
can you show client code for fetch
@Toyger can you show client code for fetch
Acorn-plum gallOP
Here it is, the api also doesn't work using postman, or thunder client either whereas the other API routes all do.
async function uploadFile() {
if (file) {
setIsLoading(true);
const formData = new FormData();
formData.append("file", file);
formData.append("fileName", fileName);
await fetch("/api/client/upload", {
method: "POST",
body: formData,
})
.then((response) => response.json())
.then((data) => {
if (data.status === 201) {
toast.success("File uploaded successfully");
router.refresh();
} else {
toast.error("Error uploading your file. Please try again.");
}
})
.catch((error) => {
console.error("Error uploading file:", error);
toast.error("Network error. Please check your connection.");
})
.finally(() => {
setIsLoading(false);
clearFile();
});
}
}Acorn-plum gallOP
Correct
Acorn-plum gallOP
When a call is made these logs apear within the Vercel logs:
Further pointing towards to issue being related to sharp
Toyger
so it's then sharp issue, here https://github.com/lovell/sharp/issues/3870 people reccomend to downgrade to
0.32.6Answer
Acorn-plum gallOP
Thankyou, I’ll give it a go and let you know.
Acorn-plum gallOP
Thank you so much â¤ï¸