How to integrate Keycloak on local server using React (CORS problem)

Hi everyone ! have a question concerning the integration of Keycloak.

Right now I created my realm, with users etc…
I’m developing an app on local using Vite for my front end (port 5173) and a local server to request datas from API (port 3000)

I have some CORS issues when I try to protect my API routes, and can’t figure why.
I’ve set up on my app.js all the informations needed, set the middleware and cors and then, on my routes, added keycloak.protect().
I’ve added localhost:3000 and localhost:5173 in my keycloak server (already hosted on the net)

However, I keep having CORS issues like:

redirected from ‘http://localhost:3000/connectors/api/profile’) from origin ‘http://localhost:5173’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

Any tips on how to solve this issue, so I can test to run my app locally please ?

Hi @matthieug the CORS error you’re seeing is because the browser is making a request to a different origin: to http://localhost:3000 from http://localhost:5173

You can fix this by using the Vite dev server proxy. Here’s an example. Tweak it to your needs:

Hi !
First of all, thanks a lot for your reply !

Here is the code of my vite.config.ts file :slight_smile:

import { defineConfig } from "vite";
import react from "@vitejs/plugin-react-swc";
import jsconfigPaths from 'vite-jsconfig-paths'

export default defineConfig({
	root: __dirname,
	plugins: [
		react(),
		jsconfigPaths(),
	],
	server: {
		open: true,
		strictPort: true,
		port: 5173,
		// proxy: {
		// 	'/connectors/api': {
		// 		target: 'http://localhost:3000',
		// 		changeOrigin: true,
		// 		secure: false,
		// 	},
		// },
		proxy: {
			'/connectors/api': {
				target: 'http://localhost:3000',
				changeOrigin: true,
				rewrite: (path) => {
					return path.replace(/^\/connectors\/api/, '/connectors/api');
				}
			}
		},
	},
});

I’ve tested multiple things, but I keep getting CORS errors sadly :confused:
Maybe I missed something ?

If you need more informations about some files, just tell me and i’ll paste what I can share.

Thanks again

Could you paste the code that is making a request to that /connectors/api endpoint ?

My hunch is that the url looks something like this:

# change me
const url = 'http://localhost:3000/connectors/api/profile';

fetch(url)
  .then((response) => {
    // ...
  })
  .catch((error) => {
    // ...
  });

But instead should be changed to /connectors/api/profile

That way it uses the current origin, aka the vite dev server origin of http://localhost:5173, which will be proxied to your api endpoint.

1 Like

Guys, your issue is not related to Keycloak, it’s a general issue when using cross-origin requests.
Please use a proper forum, so that we can keep our focus on Keycloak-only related topics!
Thanks for your understanding.

Hi,

Sounds like zach-betz-hin found the problem. Indeed, the person I worked with put localhost:3000 directly in his code, and that was the issue…
Here is what it looked like @zach-betz-hln

const apiConnectorsUrl = import.meta.env.VITE_CONNECTORS_API_URL

export default async function getConnectorsList() {
    return axios
        .get(apiConnectorsUrl + '/list',
            // {
            //     headers: {
            //         "Authorization": Queries.createHeaderAuthorization(),
            //     }
            // }
        )
        .then(res => {
            return res.data
        })
        .catch(error => {
                Errors.showError(error)
                return error.response
            }
        )
}

with VITE_CONNECTORS_API_URL being “http://localhost:3000/connectors/api

Sorry for this topic not really being Keycloak related, and thanks to point this out

2 Likes

@matthieug glad it’s resolved :+1:

@dasniko noted.

2 Likes