Next.js Discord

Discord Forum

Socket.io with next.js and express.js

Answered
Cape lion posted this in #help-forum
Open in Discord
Cape lionOP
How to set up socket.io with next.js frontend and express.js backend apps separately? I am currently cors error from next.js app url.

6 Replies

Black carp
Show ur current express setup u can add cors config to socket
@Black carp Show ur current express setup u can add cors config to socket
Cape lionOP
const app: Express = express();
const server = http.createServer(app);
const io = new Server(server);

dotenv.config();

const port = process.env.PORT 8000;
const DB_URI = process.env.MONGO_DB_URI
"";

app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(
cors({
origin: process.env.FRONTEND_URL || http://localhost:3000,
credentials: true,
})
); //cors
app.use("/uploads", express.static(path.join(__dirname, "uploads")));
app.use(morgan("dev"));
Black carp
Where is socket setup?
Black carp
Answer
Black carp
Check the docs for handling cors in socket
@Black carp Where is socket setup?
Cape lionOP
I added these before the previous code. Doesn't cors packages handle cors for socket.io as well?

import express, { Express, Request, Response, NextFunction } from "express";
import mongoose from "mongoose";
import path from "path";
import http from "http";
import dotenv from "dotenv";
import cors from "cors";
import morgan from "morgan";
import { Server } from "socket.io";