I'm using passport-twitch for users to be able to add enter their Twitch accounts in order to be able to collect the profileID and so the number of followers of the Twitch channel in my next js and node js project, but I'm getting a CORS error when submitting the form, even though I'm including the correct clientID in the request. Any help would be greatly appreciated as I've been struggling with this for several days now.
I've created this middleware called twitchAuth for passport:
import passport from "passport";
import TwitchStrategy from "passport-twitch-helix";
import Usuario from "../models/Usuario.js";
const twitchPassport = passport;
twitchPassport.use(
"twitch",
new TwitchStrategy.Strategy(
{
clientID: process.env.CLIENT_ID,
callbackURL: process.env.CALLBACK_URL,
scope: "user_read",
},
function (accessToken, refreshToken, profile, done) {
console.log(profile.id);
/* Usuario.findOrCreate({ twitchId: profile.id }, function (err, user) {
return done(err, user);
}); */
},
),
);
export default twitchPassport;
This is my routes file:
import express from "express";
import twitchPassport from "../middleware/twitchAuth.js";
router.put("/perfil/:id", editarPerfil);
router.get(
"/followers",
twitchPassport.authenticate("twitch", { forceVerify: true }),
(req, res) => {
// Aquí puedes realizar la lógica para obtener los seguidores del usuario de Twitch
res.status({ followers: 100 }); // Ejemplo de respuesta JSON con la cantidad de seguidores
},
);
router.get(
"/auth/twitch/callback",
twitchPassport.authenticate("twitch", { failureRedirect: "/" }),
function (req, res) {
// Successful authentication, redirect home.
res.redirect("/");
},
);
export default router;
This is my index.js file for the express server:
import express from "express";
import http from "http";
import dotenv from "dotenv";
import cors from "cors";
import conectarDB from "./config/db.js";
import usuarioRoutes from "./routes/usuarioRoutes.js";
import configureSocket from "./socket.js";
dotenv.config();
const app = express();
app.use(express.json());
const PORT = process.env.PORT || 4000;
conectarDB();
// Configurar CORS
const whitelist = [process.env.FRONTEND_URL];
const corsOptions = {
origin: function (origin, callback) {
if (whitelist.includes(origin)) {
// Puede consultar la API
callback(null, true);
} else {
// No está permitido
callback(new Error("Error de Cors"));
}
},
};
app.use(cors(corsOptions));
// Routing
app.use("/api/usuarios", usuarioRoutes);
app.use("/api/twitch", usuarioRoutes); // Agrega la ruta de Twitch aquí antes de las rutas protegidas
// Crear servidor HTTP
const server = http.createServer(app);
// Configurar Socket.IO
configureSocket(server);
// Iniciar servidor
server.listen(PORT, () => {
console.log(`Corriendo en el puerto ${PORT}`);
});