Reputation: 181
Is is possible to implement dynamic route in next.js Server Side Rendering fetched data? All examples and explanations of dynamic routes in next I see are set in Static Side Generation...
I am building a social media like application with user profile pages that contains image, video and comment posts, data which is dynamicaly updated by users (profile owner or his followers). Server arquitecture being implemented aside in node.js express, typeorm postgress. Having chosen Next.js for frontend, I understand "Server Side Rendering" is required for dynamically rendering updated data from server to address my app data fetchig demand. But all projects I came accross using dynamic routes are in SSG, usually suited for static data.
Thanks!
Upvotes: 3
Views: 3547
Reputation: 265
I'll post here my example for this specific case, turning a getStaticProps profile page into a getServerSideProps page.
Here is the static page :
// To statically generate dynamic links for each User
export async function getStaticPaths() {
const userSlugs = []
const request = await getDocs(collection(db, "users"))
request.forEach((doc) => {
userSlugs.push({
params: { id: doc.id },
})
})
return {
paths: userSlugs,
fallback: false,
}
}
// SSG page optimised for SEO
export async function getStaticProps({ params }) {
// Fetching different type of data from the firestore database
if (docSnap.exists()) {
return {
props: {
userId: params.id,
userData: JSON.parse(JSON.stringify(docSnap.data())),
/// other data
}
}
} else {
console.log("No such document!");
}
}
Here is the SSR page :
export async function getServerSideProps({ params }) {
const { id } = params
const selectedActions = []
// Getting the user's general data
const docRef = doc(db, "users", id);
const docSnap = await getDoc(docRef);
// Getting the user's selectedActions
const req1 = await getDocs(collection(db, "users", id, "selectedActions"))
req1.forEach((doc) => {
selectedActions.push({
id: doc.id, data: doc.data()
})
})
if (docSnap.exists()) {
return {
props: {
userId: id,
userData: JSON.parse(JSON.stringify(docSnap.data())),
// other data
}
}
} else {
console.log("No such document!");
}
}
Hope it will help :)
Upvotes: 0
Reputation: 709
in your dynamic route page /pages/[id].js use getServerSideProps alone without getStaticPaths this will render the page server side on every request.
Upvotes: 1