Next.js Discord

Discord Forum

CORS in NextJS

Unanswered
LazeyLove posted this in #help-forum
Open in Discord
I have a struggle with CORS in next js after research a lot of document on the internet. Here is my code
import { withIronSessionApiRoute } from 'iron-session/next';
import { sessionOptions } from '@libs/session';
import { NextApiRequest, NextApiResponse } from 'next';
import { idp, sp } from '@libs/saml';

export default withIronSessionApiRoute(loginRoute, sessionOptions);

async function loginRoute(req: NextApiRequest, res: NextApiResponse) {
  try {
    const { id, context } = sp.createLoginRequest(idp, 'redirect');
    console.log("process.env.IDP_METADATA", process.env.IDP_METADATA)
    console.log(`login request id:`, id);
    console.log(`login request context:`, context);
    return res.redirect(context);
  } catch (error) {
    console.log(error);
    res.status(500).json({ message: (error as Error).message });
  }
}

The CORS happend in line res.redirect when i want to redirect to localhost:8000 ( my nextjs app run in port 3000 ). Has anyone know how to fix it? Hope for your answer.

8 Replies

Horse guard wasp
// next.config.js module.exports = { async rewrites() { return [ { source: '/api/:path*', destination: 'https://api.example.com/:path*', }, ] }, };
add your route in next.config.js
like this
@Horse guard wasp `// next.config.js module.exports = { async rewrites() { return [ { source: '/api/:path*', destination: 'https://api.example.com/:path*', }, ] }, };`
sorry, i want to redirect to third party (keycloak), so it's not have source. The uri i want to redirect is http://localhost:8080/realms/SAML/protocol/saml?SAMLRequest={code} So how to fix CORS in this situation
you need to tweak the keycloak HTTP server to return a HTTP response with

Access-Control-Allow-Origin: http://localhost:3000

basically it has nothing to do with the Next.js server (Origin side)
actually i've never heard about Keycloak. Just googled it.