dsb-norge / vue-keycloak-js

A Keycloak plugin for Vue 2
https://www.dsb.no
ISC License
272 stars 99 forks source link

Server side rendering support #34

Open igrslv opened 5 years ago

igrslv commented 5 years ago

The NuxtJS framework has server-side rendering out of the box (in universal mode) and there are some errors since the lib uses window global variable. The code that uses window must be wrapped with the condition like if (process.browser) { ... } but there might be something else. Thanks!

nlien commented 5 years ago

You're right. The plugin doesn't take SSR into account. This is something I hope to get implemented. Can't really say when at the moment...

stevenferrer commented 4 years ago

Here's my setup:

plugin/vue-keycloak.js

import Vue from 'vue'
import VueKeyCloak from '@dsb-norge/vue-keycloak-js'

// You can also pass in options. Check options reference below.
Vue.use(VueKeyCloak, {
  config: {
    url: 'http://keycloakserver/auth',
    realm: 'my-realm',
    clientId: 'my-client'
  },
  init: {
    onLoad: 'login-required',
    checkLoginIframe: false
  },
  onReady(keycloak) {

  }
})

nuxt.config.js

{
  ...
  plugins: [
    { src: '~/plugins/vue-keycloak.js', mode: 'client' }
  ]
  ...
}

I'm also getting warnings with Nuxt.js like the one below:

[Vue warn]: The client-side rendered virtual DOM tree is not matching server-rendered content. This is likely caused by incorrect HTML markup, for example nesting block-level elements inside <p>, or missing <tbody>. Bailing hydration and performing full client-side render.

For now, I'm using the non-ssr mode of Nuxt to get around this.

Nuxt.js v2.11.0 Keycloak v8.0.1

BernardZhao commented 4 years ago

I think that to support server side rendering this plugin has to take more than just window into account, because things like fetching the /config from the site itself doesn't really make sense when the site is being rendered. It should really be done on the client, and therefore init must be done there as well. The problem here is that if the keycloak object is only created then, putting references to the $keycloak property with things like login and logout into your code wouldn't resolve when being rendered. I believe this is why in @stevenferrer's case even when running the plugin on the client side only it still fails, and I tried running the plugin client side only on Gridsome and got the same issue. I would make a PR myself if this was an easy fix, but I can't think of a simple way of making this work.