sathish kamaraj
sathish kamaraj

Reputation: 21

How to fix: Cannot read property 'keycloak-token' of undefined in node js?

I have created realm and client. keycloak json is placed in root folder. still i'm getting the error like,

Cannot read property 'keycloak-token' of undefined
TypeError: Cannot read property 'keycloak-token' of undefined at SessionStore.get (C:\Users\...\node_modules\keycloak-connect\stores\session-store.js:24:58)
var session = require('express-session');
var Keycloak = require('keycloak-connect');

var memoryStore = new session.MemoryStore();
var keycloak = new Keycloak({ store: memoryStore });

Upvotes: 2

Views: 3412

Answers (1)

danialk
danialk

Reputation: 1453

You get this error when you set app.use(keycloak.middleware()) and don't configure the session store. The keycloak-connect library is trying to read a keycloak-token value from the session that hasn't been configured. You can circumvent the error by supplying an Authorization header for example Authorization: Bearer 123 but the solution when using a session store is to configure it.

For a complete example see node_modules/keycloak-connect/example/index.js in your project's dependencies. A minimal example with resource protection using multiple middlewares in the route handler below.

Be advised however, that:

MemoryStore, is purposely not designed for a production environment. It will leak memory under most conditions, does not scale past a single process, and is meant for debugging and developing.

const express = require('express')
const app = express()
const session = require('express-session');
const Keycloak = require('keycloak-connect');
var memoryStore = new session.MemoryStore();
var keycloak = new Keycloak({ store: memoryStore });

// Configure session
app.use(session({
  secret: 'mySecret',
  resave: false,
  saveUninitialized: true,
  store: memoryStore
}));

// Attach middleware
app.use(keycloak.middleware());

// Attach route handler for home page
app.get('/', keycloak.protect(), (req, res, next) => {
  res.json({status: 'ok'})
})

// Start server
app.listen(3005)

Upvotes: 4

Related Questions