Next.js Discord

Discord Forum

Vercel Deployment doesn't match localhost

Answered
Large oak-apple gall posted this in #help-forum
Open in Discord
Large oak-apple gallOP
Hi, I have a NextJS React app that I have deployed to Vercel and the app uses a MongoDB database. I have a button that creates a post which should then be displayed in my Feed component. It works fine in the localhost:3000 but not on the deployed app. The weird thing is in the deployed app, when I create a new post, the post is created in MongoDB but doesn't show in the feed. It seems like everything works, the post shows up in MongoDB but the Feed just doesn't update. If I redeploy it though, the post does show up but I have to keep redeploying the app for the Feed to update.

Does anyone know why this is happening. I did the whole process with the console open and I didn't get any errors. This may not have been the best explanation so I can provide more details if needed. Any help is appreciated, thanks!
Answered by New Zealand Heading Dog
Nice. I've had to fix this same issue before. Here's how I done it:

In the "/api/prompt/route.js" file add this at the bottom:

export const dynamic = 'force-dynamic';
View full answer

77 Replies

most probably it is not dynamic but static
Large oak-apple gallOP
what do you mean by that?
How do I change it from dynamic to dynamic
plz share your codes that retrieve mongo
Large oak-apple gallOP
import mongoose from "mongoose";

let isConnected = false; // track the connection

export const connectToDB = async () => {
mongoose.set("strictQuery", true); // removes warnings in console

if (isConnected) {
console.log("MongoDB is already connected");
return; // break out of const connectToDB function
}

try {
await mongoose.connect(process.env.MONGODB_URI, {
dbName: "workhubb",
useNewUrlParser: true,
useUnifiedTopology: true,
});

isConnected = true;

console.log("MongoDB connected");
} catch (error) {
console.log(error);
}
};
Not sure how to code block it
and Vercel build log
Large oak-apple gallOP
i mean codes of endpoints
Large oak-apple gallOP
So like my route.js files?
yes
Large oak-apple gallOP
Here is the route.js file that gets posts by id:

import Post from "@models/postSchema";
import { connectToDB } from "@utils/database";

// Routes for editing and deleting posts that belong to the session user. This makes it so that you can access
// each individual post by its ID and edit or delete it.

// GET
export const GET = async (request, { params }) => {
try {
await connectToDB(); // first connect to the mongoDB database
const post = await Post.findById(params.id).populate("creator"); // get all the posts from the database
if (!post) return new Response("Post not found", { status: 404 }); // return a 404 error if the post is not found

return new Response(JSON.stringify(post), { status: 200 }); // return the posts as a JSON string
} catch (error) {
return new Response("Failed to get posts", { status: 500 }); // return a 500 error if something went wrong
}
};

// PATCH (update)
export const PATCH = async (request, { params }) => {
const { post, tag, title, amount } = await request.json();

try {
await connectToDB();

const existingPost = await Post.findById(params.id);

if (!existingPost) return new Response("Post not found", { status: 404 });

existingPost.post = post;
existingPost.tag = tag;
existingPost.title = title;
existingPost.amount = amount;

await existingPost.save();

return new Response(JSON.stringify(existingPost), { status: 200 });
} catch (error) {
console.log(error);
return new Response("Failed to update post", { status: 500 });
}
};

// DELETE
export const DELETE = async (request, { params }) => {
try {
await connectToDB();

// Find the post by ID and remove it
await Post.findByIdAndRemove(params.id);

return new Response("Post deleted successfully", { status: 200 });
} catch (error) {
console.log(error);
return new Response("Error deleting post", { status: 500 });
}
};
I think that might be all you need?
Here is my Feed component where the issues seem to be happening:
so the endpoint is /api/post ?
Large oak-apple gallOP
So the endpoint for the Feed is just http://localhost:3000, but then when you go to create a post the form endpoint is http://localhost:3000/create-post. For the individual posts it would be /api/[id]/post
There is a dynamic id for each post
I can send you the github repo if you'd like
New Zealand Heading Dog
I'm guessing you are doing the Full Stack Next.js 13 Course by JavaScript Mastery?
Large oak-apple gallOP
Yeah
I've made some changes to the overall project but it should follow the same structure.
from your codes, the endpoint looks like /api/post. then from build log, whch is a static page.
Large oak-apple gallOP
so what would I have to fix it, and why would it work in localhost but not in the deployed version
you run it with development mode, npm dev locally on ur machine?
Large oak-apple gallOP
yeah
with dev mode, pages are always generated dynamically.
if u build and start, it will happen even locally ur machine
@Large oak-apple gall Yeah
New Zealand Heading Dog
Nice. I've had to fix this same issue before. Here's how I done it:

In the "/api/prompt/route.js" file add this at the bottom:

export const dynamic = 'force-dynamic';
Answer
do u use App Router instead of Page Router?
Large oak-apple gallOP
So like this:

import Post from "@models/postSchema";
import { connectToDB } from "@utils/database";

// This file is the API route that retrives a post from the database which is being mapped
// in with the Feed Component. This route is called everytime to produce each individual post

export const GET = async (request) => {
try {
await connectToDB(); // first connect to the mongoDB database
const posts = await Post.find({}).populate("creator"); // get all the posts from the database
return new Response(JSON.stringify(posts), { status: 200 }); // return the posts as a JSON string
} catch (error) {
return new Response("Failed to get posts", { status: 500 }); // return a 500 error if something went wrong
}
};

export const dynamic = "force dynamic";
@tafutada777 do u use App Router instead of Page Router?
Large oak-apple gallOP
no im not using app router
so @New Zealand Heading Dog, should I include this in all of my routes?
@Large oak-apple gall so <@438740932356079626>, should I include this in all of my routes?
New Zealand Heading Dog
Just the routes that have to be fetched dynamically such as posts. In the vercel build log, it will indicate what routes are generated statically, dynamically, etc. if I remember correctly.
Large oak-apple gallOP
Okay thank you, let me give it shot
Large oak-apple gallOP
That still doesnt seem to work, is there anywhere else I would have to add the export const dynamic?
@New Zealand Heading Dog would I have to add that to the route.js within the api/post/[id] folder?
Also, in the build log, it still says that api/post is static
@Large oak-apple gall <@438740932356079626> would I have to add that to the route.js within the api/post/[id] folder?
New Zealand Heading Dog
That shouldn't be needed. Are you using the App router like in the tutorial as that snippet of code should work?
Large oak-apple gallOP
Yes I should be
where would that be located?
Im sorry Im still learning Next so I dont know too much yet
@Large oak-apple gall where would that be located?
New Zealand Heading Dog
So, the app router means that your pages are structured like so:

app
 - api
  - prompt
   - route.js
Large oak-apple gallOP
oh yeah im using that
@Large oak-apple gall oh yeah im using that
New Zealand Heading Dog
Ok, try redeploying your application.
Large oak-apple gallOP
I just redployed it, in the build log it still says api/post is static:
New Zealand Heading Dog
Is your GitHub repository public?
Large oak-apple gallOP
yeah would you like me to send it to you?
@Large oak-apple gall yeah would you like me to send it to you?
New Zealand Heading Dog
Yeah, link it in here please.
Large oak-apple gallOP
The project wont look the same, i changed a few features to tailor them to my needs. I uses "posts" instead of "prompts"

https://github.com/ay-chang/workhubb
New Zealand Heading Dog
Could you try setting this line:

<PostCardList data={displayedPosts}/>

To
<PostCardList data={allPosts} />
Large oak-apple gallOP
Sure
still doesnt update the feed
New Zealand Heading Dog
Also, try changing this:
const response = await fetch("/api/post");

To
const response = await fetch("/api/post", { 
       cache: 'no-store' 
});
Large oak-apple gallOP
okay and it should be fine to change the previous line you sent back to displayedPosts?
Large oak-apple gallOP
should I remove the force dynamic or keep that there
@Large oak-apple gall should I remove the force dynamic or keep that there
New Zealand Heading Dog
Keep it, for now, to see if the combination of using
 cache: no-store
and
 export const dynamic = 'force-dynamic'
works or not.
Large oak-apple gallOP
nope, still doesnt work
also, in the build log it still says that the api/post is static
New Zealand Heading Dog
In your "/api/post/route.js" file it should be:

export const dynamic = 'force-dynamic'

NOT THIS
export const dynamic = 'force dynamic'
Large oak-apple gallOP
omg...
let me see if that works
it worked, thank you so much for the help and i apologize for that mistake.
@Large oak-apple gall it worked, thank you so much for the help and i apologize for that mistake.
New Zealand Heading Dog
That's brilliant. It's all good, mistakes happen. Glad you managed to fix it and I'm glad I could help. Don't be deterred because of a simple typo, though. Those are easier to make than you think 😂
Large oak-apple gallOP
Haha, again thank you so much!
@Large oak-apple gall Haha, again thank you so much!
New Zealand Heading Dog
All good, enjoy the tutorial. I really enjoyed it, I certainly learned alot from it.
Whiteleg shrimp
can anyone help me with my q?
@Whiteleg shrimp can anyone help me with my q?
New Zealand Heading Dog
Is it related to this? If not, you’ll have to make a separate forum post to receive the proper support for your question.
Whiteleg shrimp
no not related. i made one, but this one seems to pop up on top with the most comments
@Whiteleg shrimp no not related. i made one, but this one seems to pop up on top with the most comments
New Zealand Heading Dog
It depends when people are online to help and of they are able to help, give it time. It could take a while to get a reply.
@New Zealand Heading Dog In your "/api/post/route.js" file it should be: js export const dynamic = 'force-dynamic' ***NOT THIS*** js export const dynamic = 'force dynamic'
New Zealand Heading Dog
@Large oak-apple gall If you want to mark this message as the solution, that'd be great so that people know that you've fixed this error/issue.
Large oak-apple gallOP
yeah im trying to figure out how to do that right now
got it
@Large oak-apple gall got it
New Zealand Heading Dog
Brilliant. Have nice day/night and I hope you enjoy JavaScript Mastery's tutorial.
Whiteleg shrimp
whats javascript mastery tutorial
@Whiteleg shrimp whats javascript mastery tutorial
New Zealand Heading Dog
It's someone who provides tutorials on YouTube. This specific forum post was based upon the "Next.js 13 Full Course" tutorial which was provided and created by JavaScript Mastery on YouTube.