Please note: although this question mentions OIDC I believe this to be a pure JS/React question at heart, and does not require experience with React OIDC to answer!
I have a React app with the following index.jsx
:
import React from "react";
import ReactDOM from "react-dom";
import { createRoot } from 'react-dom/client';
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import { AuthProvider } from "react-oidc-context";
import Dashboard from "./users/Dashboard";
import AcceptInvitation from "./users/AcceptInvitation";
import ExpiredToken from "./users/ExpiredToken";
import AboutUs from "./web/AboutUs";
import AccountSettings from "./users/AccountSettings";
import ErrorBoundary from './ErrorBoundary';
import { keycloakBaseUrl } from './keycloak/KeycloakConstants';
const oidcConfig = {
authority: keycloakBaseUrl,
client_id: process.env.REACT_APP_KEYCLOAK_CLIENT,
redirect_uri: process.env.REACT_APP_KEYCLOK_REDIRECT_URL
};
const container = document.getElementById('root');
const root = createRoot(container);
root.render(
<ErrorBoundary>
<Router>
<AuthProvider {...oidcConfig}>
<Routes>
<Route path="/about-us" element={<AboutUs />} />
<Route path="/accept-invitation" element={<AcceptInvitation />} />
<Route path="/account-settings" element={<AccountSettings />} />
<Route path="/dashboard" element={<Dashboard />} />
<Route path="/error" element={<ErrorBoundary />} />
<Route path="/expired-token" element={<ExpiredToken />} />
</Routes>
</AuthProvider>
</Router>
</ErrorBoundary>
);
That KeycloakConstants.js
looks like:
const KEYCLOAK_HOST_AND_PORT = process.env.KEYCLOAK_HOST_AND_PORT;
const KEYCLOAK_REALM = process.env.KEYCLOAK_REALM;
const keycloakBaseUrl = `${KEYCLOAK_HOST_AND_PORT}/realms/${KEYCLOAK_REALM}`;
console.log("keycloakBaseUrl = " + keycloakBaseUrl);
console.log(process.env);
export { keycloakBaseUrl };
When I try going to an authenticated page/route I get an error that indicates my OIDC info isn’t being loaded properly:
“Oops… Invalid response Content-Type: text/html; charset=utf-8, from URL: undefined/realms/undefined/.well-known/openid-configuration“
When I open Developer Tools to view the console log output from my KeycloakConstants.js
page I see:
keycloakBaseUrl = undefined/realms/undefined
{NODE_ENV: 'development', PUBLIC_URL: '', WDS_SOCKET_HOST: undefined, WDS_SOCKET_PATH: undefined, WDS_SOCKET_PORT: undefined, …}
FAST_REFRESH
:
true
NODE_ENV
:
"development"
PUBLIC_URL
:
""
REACT_APP_API_GATEWAY
:
"http://localhost:9200"
REACT_APP_FULL_NAME
:
"My app"
WDS_SOCKET_PORT
:
undefined
[[Prototype]]
:
Object
So process.env
is loading just fine, just not my individual KEYCLOAK_HOST_AND_PORT
and KEYCLOAK_REALM
env vars. Can anyone spot where I’m going awry? Do I need to add anything at the top of KeycloakConstants.js
to get it to load the env vars properly?