Next JS – MongoDB / 504 GATEWAY_TIMEOUT Vercel at Dynamic Route

huangapple go评论67阅读模式
英文:

Next JS - MongoDB / 504 GATEWAY_TIMEOUT Vercel at Dynamic Route

问题

I am using Mongo DB shared clustered and Vercel free.
First of all, locally there is no timeout issues, my MongoDB connection uses mongoose so i am calling always the same connection. Moreover, at vercel the problem is the first time i connect, afterwards the page caches the route and in 2 seconds maximum it loads with no problem.
Dynamic pages in my route are generated by SSG, in this case its for courses and classes, the route looks like this https://www.mateomolfino.com/src/courses/1/1.

mongodb.js

if (!process.env.MONGODB_URI) {
   throw new Error('Invalid/Missing environment variable: "MONGODB_URI"')
 }

 const uri = process.env.MONGODB_URI
 const options = {}

 let client
 let clientPromise

 if (process.env.NODE_ENV === 'development') {
 if (!global._mongoClientPromise) {
 client = new MongoClient(uri, options)
 global._mongoClientPromise = client.connect()
 }
 clientPromise = global._mongoClientPromise
 } else {
   client = new MongoClient(uri, options)
  clientPromise = client.connect()
 }

SSR

export async function getServerSideProps(context: any) {

await db()
const { params, query, req, res } = context
const session = await getSession({ req })
const cookies = parseCookies(context)
const userCookie = cookies?.user ? JSON.parse(cookies.user) :
session?.user
const email = userCookie?.email
const { classId, id } = params
const clase = await getClassById(classId, id)
const user = await updateActualCourseSS(email, id, classId)

return {
props: { clase, user }
}
}

getClassById

import connectDB from "../../../config/connectDB"
import Course from "../../../models/courseModel"
import User from "../../../models/userModel"
import Class from "../../../models/classModel"
import bcrypt from "bcryptjs"

export async function getClassById(id, courseId) {
try {
const res = await Class.where('id').equals(id).populate({
path: 'course', match: {id: courseId}}).exec()
const courseToSend = res.filter(r => r.course != null)

 const clase = JSON.parse(JSON.stringify(courseToSend[0]))
 return clase
 } catch (err) {
  console.log(err)
 }

}

updateActualCourseSS

export async function updateActualCourseSS(email: string,
courseId: string, actualChapter: number) {
try {
console.log('connected')
const user: any | null = await User.findOne({ email: email
}).exec()
const courseDB: CoursesDB | null = await Course.findOne({ id:
courseId}).exec()

const index = user?.courses.findIndex((course: CourseUser) => 
course.course.valueOf() === courseDB?._id.valueOf())

index != null && user != null ? 
user.courses[index].actualChapter = actualChapter : null

user.courses[index].actualTime = 0;

await user?.save()

return JSON.parse(JSON.stringify(user));

 } catch (err) {
  console.log(err)
 }
}
英文:

I am using Mongo DB shared clustered and Vercel free.
First of all, locally there is no timeout issues, my MongoDB connection uses mongoose so i am calling always the same connection. Moreover, at vercel the problem is the first time i connect, afterwards the page caches the route and in 2 seconds maximum it loads with no problem.
Dynamic pages in my route are generated by SSG, in this case its for courses and classes, the route looks like this https://www.mateomolfino.com/src/courses/1/1.

mongodb.js

if (!process.env.MONGODB_URI) {
   throw new Error('Invalid/Missing environment variable: 
 "MONGODB_URI"')
 }

 const uri = process.env.MONGODB_URI
 const options = {}

 let client
 let clientPromise

 if (process.env.NODE_ENV === 'development') {
 if (!global._mongoClientPromise) {
 client = new MongoClient(uri, options)
 global._mongoClientPromise = client.connect()
 }
 clientPromise = global._mongoClientPromise
 } else {
   client = new MongoClient(uri, options)
  clientPromise = client.connect()
 }

# SSR
# 
export async function getServerSideProps(context: any) {

  await db()
  const { params, query, req, res } = context
  const session = await getSession({ req })
  const cookies = parseCookies(context)
  const userCookie = cookies?.user ? JSON.parse(cookies.user) : 
  session?.user
  const email = userCookie?.email   
  const { classId, id } = params
  const clase = await getClassById(classId, id)
  const user = await updateActualCourseSS(email, id, classId)

  return {
    props: { clase, user  }
  }
 } 

getClassById

 import connectDB from "../../../config/connectDB" 
 import Course from "../../../models/courseModel"
 import User from "../../../models/userModel"
 import Class from "../../../models/classModel"
 import bcrypt from "bcryptjs"

 export async function getClassById(id, courseId) {
   try {
     const res = await Class.where('id').equals(id).populate({ 
     path: 'course', match: {id:      courseId}}).exec()
     const courseToSend = res.filter(r => r.course != null)

     const clase = JSON.parse(JSON.stringify(courseToSend[0]))
     return clase
     } catch (err) {
      console.log(err)
     }
  }

updateActualCourseSS

  export async function updateActualCourseSS(email: string, 
   courseId: string, actualChapter: number) {
   try {
    console.log('connected')
    const user: any | null = await User.findOne({ email: email 
    }).exec()
    const courseDB: CoursesDB | null = await Course.findOne({ id: 
    courseId}).exec()

    const index = user?.courses.findIndex((course: CourseUser) => 
    course.course.valueOf() === courseDB?._id.valueOf())

    index != null && user != null ? 
    user.courses[index].actualChapter = actualChapter : null

    user.courses[index].actualTime = 0;

    await user?.save()

    return JSON.parse(JSON.stringify(user));

     } catch (err) {
      console.log(err)
     }
    }

答案1

得分: 1

你必须前往 "vercel->integrations" 页面:https://vercel.com/dashboard/integrations 并将 Vercel 与 MongoDB Atlas 连接起来。

英文:

You must go to "vercel->integrations": https://vercel.com/dashboard/integrations

1: https://vercel.com/dashboard/integrations and connect Vercel with MongoDB Atlas.

huangapple
  • 本文由 发表于 2023年3月9日 21:24:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/75685224.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定