1

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}`);
});
Phil
  • 157,677
  • 23
  • 242
  • 245
Lucian
  • 21
  • 4
  • What exactly is the error? FYI, you can pass an array of origins to the CORS middleware; there's no need to use `whitelist.includes()`... `origin: whitelist` – Phil Jul 09 '23 at 22:52
  • Thanks Phil. I'm actually using the whitelist for other routes that need it. The exact error I'm getting says the following: " (redirected from 'http://localhost:4000/api/twitch/followers') from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource." – Lucian Jul 09 '23 at 22:55
  • Please include the full error. You seem to have omitted the first part – Phil Jul 09 '23 at 22:55
  • Sorry, I ommitted that part because it includes my personal clientID. Here's the full error without that part: – Lucian Jul 09 '23 at 23:00
  • Does this answer your question? [Access-Control-Allow-Origin equals origin but the browser still denies access... why?](https://stackoverflow.com/questions/69494027/access-control-allow-origin-equals-origin-but-the-browser-still-denies-access) – Phil Jul 09 '23 at 23:02
  • Access to XMLHttpRequest at 'https://www.twitch.tv/login?client_id=[clientID]&redirect_params=client_id%3D[clientID]%26force_verify%3Dtrue%26redirect_uri%3Dhttp%253A%252F%252Flocalhost%253A3000%252Fauth%252Ftwitch%252Fcallback%26response_type%3Dcode%26scope%3Duser_read' (redirected from 'http://localhost:4000/api/twitch/followers') from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. – Lucian Jul 09 '23 at 23:03
  • Thanks Phil, I've just read that post but I'm not quite sure how I should apply it in my code. Do you mean I should try changin the url in the index.js file that I've set for the Express server? – Lucian Jul 09 '23 at 23:07
  • I don't think you can launch the Twitch (or any other OAuth) authentication strategy for API requests since it requires a user-driven OAuth flow. I think [this answer](https://stackoverflow.com/a/63736799/283366) might help – Phil Jul 09 '23 at 23:19

0 Answers0