To deploy the full stack web applications follow this steps : -
First , you have to deploy backend and frontend separately, when on vercel -> create a project, import your repo, and edit the root to be frontend first, add environment variables (yes you have to create an env variable,
VITE_BACKEND_URL
and give it the valuehttp://localhost:3000/api/v1
(for the local env) and your backend url once it is deployed , click on deploy, and this way your frontend will be deployed . Now, before deploying your backend, make the following changesAt the root in backend, create an api folder and shift your index.ts (main server file in which your server is defined, and remember it should be named as
index.ts
), Because vercel says, the entry point to your server should be inroot/api/index.ts
.Then create a vercel.json file at the root of your backend and paste this .
{
"version": 2,
"builds": [
{
"src": "api/index.ts",
"use": "@vercel/node"
}
],
"routes": [
{
"src": "/(.*)",
"dest": "/api/index.ts",
"methods": ["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"],
"headers": {
"Access-Control-Allow-Credentials": "true",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET,OPTIONS,PATCH,DELETE,POST,PUT",
"Access-Control-Allow-Headers": "X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version"
}
}
]
}
The CORS middleware should be present in index.ts
file, and should be above all other middlewares:
app.use(
cors({
origin: env.FRONTEND_URL,
credentials: true,
})
);
There may arise a cookie setting problem that your backend won't be able to set cookies on the client hence hampering your normal flow.
So set the cookie sameSite attribute to "none", there can be security implications .
res.cookie("Bearer", token, {
httpOnly: true,
secure: true,
sameSite: "none",
});
Now everything seems to be set, push all the changes, and now go to the vercel dashboard, create a new project, name it
yourproject-backend
maybe, and edit its root to be backend folder and add env variables in it, but this time set urFRONTEND_URL
to be the your actual deployed frontend url (Remember you need to update your env variable in your frontend deploymentVITE_BACKEND_URL
to be your actual deployed backend url later after your backend is deployed)All env variables set, click on deploy and your backend will be deployed (it shouldnt be 404 Not Found)
Now as we discussed, edit your backend's url in your frontend project and you are good to go
DONE, Check if your project runs correctly
Also u need to add a vercel.json file at your frontend's root Because there will be a problem on your frontend that when u'll refresh your page and it will throw a 404 Not Found error.
{ "rewrites": [ {"source": "/(.*)", "destination": "/"} ] }
Follow me for more such amazing blogs.