I have created a blog project using Next. When posting a new article, the API route is called with axios and the article is created in my database (MongoDB).
Everything works fine in local environement but I’ve been unable to make it work once deployed on Vercel.
I’m pretty sure it has to do with my environement variables but I’m stuck on this.
Once I submit the form, it’s loading for a few seconds, but then just redirect on /articles
page.
The code of the request:
const handleSubmit = async (formData: FormData) => {
"use server";
try {
const response = await axios.post(
`${process.env.URL}/api/articles`,
formData,
{
headers: {
"Content-Type": "multipart/form-data",
},
},
);
} catch (error: unknown) {
if (error instanceof Error) {
console.log(error.message);
} else {
console.log({ message: "Unknown error" });
}
}
redirect("/articles");
};
I have no error in my logs on Vercel:
JUL 16 12:41:31.70 - POST - 303 - next-blog-af.vercel.app - /articles/new
Here’s the link to my repo
And the link to the deployed https://next-blog-af.vercel.app/
I’ve tried several different combinations of environement variables on Vercel based on what I found on other threads but I’m still unable to make it work.
Adrien Frischknecht is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
2
After losing a lot of time trying to make this work using an API, I’ve been able to make it work by putting all the logic to post the article directly in my handleSubmit
function on my page instead of using a separate route.
It now works fine in local as well as in production.
Here’s my final code:
const handleSubmit = async (formData: FormData) => {
"use server";
try {
await connectPageToDb();
const date = new Date();
const newArticle = new Article({
title: formData.get("title"),
text: formData.get("text"),
author: formData.get("author"),
date: date,
});
const pictureToUpload: any = formData.get("picture");
const buffer = Buffer.from(await pictureToUpload.arrayBuffer());
console.log(pictureToUpload, buffer);
const result = await cloudinary.uploader.upload(
convertToBase64(pictureToUpload, buffer),
{
folder: `blog/${newArticle._id}`,
},
);
newArticle.picture = result;
await newArticle.save();
console.log("NEW ARTICLE>>>>>>>>><", newArticle);
} catch (error) {
if (error instanceof Error) {
return console.log({ message: error.message });
} else {
return console.log({ message: "Unknown error" });
}
}
redirect("/articles");
};
Adrien Frischknecht is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.