Next.js Discord

Discord Forum

Advice regarding websockets and mongodb

Unanswered
Maine Coon posted this in #help-forum
Open in Discord
Avatar
Maine CoonOP
Hey everyone! I’m working on a big project in Next.js 14 and could really use some advice on two things: setting up Websockets and MongoDB.

Websockets: I’d like to implement Websockets for real-time features like chat. What’s the best way to set this up in a Next.js app? I’m debating between using a custom Next.js server with Socket.IO or setting up a separate Node server. The main issue is that using a separate server means re-importing packages and can create some redundancy, especially since I can’t reuse code directly between servers. Any tips for efficient Websocket setup in Next.js?

MongoDB Integration: In SvelteKit, I created a simple MongoDB setup like this:

import { createConnection } from "mongoose"
import { usersSchema } from "./schemes.server"
import { building } from "$app/environment"

const db = !building ? createConnection(`....`) : null 

const users = db ? db.model("users", usersSchema) : null

export const closeConnection = () => {
  db.close()
}

export { users }

This setup was pretty intuitive—I just imported users or orders wherever I needed them, and everything worked seamlessly. I’d love to recreate a similar experience in Next.js. Does anyone have tips or best practices for organizing MongoDB code in Next.js, particularly with dynamic imports and efficient model handling?
Like I've seen some examples:
https://www.mongodb.com/developer/languages/javascript/nextjs-with-mongodb/
I'm not sure but I don't think this is good, but I don't like it compared to the sveltekit implementation.


Thanks in advance for any help!

8 Replies

Avatar
@Maine Coon
You can't use websockets in Next.js if you host your project on Vercel. As serverless connections are short while websockets require long connections.
Avatar
Maine CoonOP
I'm not hosting it on vercel.
It'll be self-hosted on a dedicated server
Avatar
well if you self-host your Next.js project, as you have control over the server you should be able to handle long-lived connection for websockets
the only reason websockets doesn't work on Vercel is because serverless connection is short while websockets require long-lived connection
Avatar
Maine CoonOP
Yea, I know that, but what is the best way to use websockets?
Have a different node server or use a custom nextjs server:https://socket.io/how-to/use-with-nextjs
Avatar
yeah, this link is good enough to refer I think
and about mongdb usage, this link should be good to start
https://vercel.com/templates/next.js/mongodb-starter