Nuxt window is not defined on server-side rendering

1.4k views Asked by At

I am trying to get the authorization headers from localStorage inside my middleware. Unfortunately this doesn't work on the first page load, because it is server-rendered.

How could I fix this?

const cookieName = 'feathers-jwt';
import { ApolloClient, createNetworkInterface } from 'apollo-client';
import 'isomorphic-fetch';

const API_ENDPOINT = 'http://localhost:3000/graphql';

const networkInterface = createNetworkInterface({ uri: API_ENDPOINT });

networkInterface.use([{
  applyMiddleware(req, next) {
    if (!req.options.headers) {
      req.options.headers = {};  // Create the header object if needed.
    }
    req.options.headers['authorization'] = window.localStorage.getItem(cookieName);
    next();
  }
}]);

const apolloClient = new ApolloClient({
  networkInterface,
  transportBatching: true
});

export default apolloClient;

source: http://dev.apollodata.com/core/network.html

1

There are 1 answers

1
MHD On BEST ANSWER

As I understand it, when you're rendering on the server you don't have access to window and document. In apps that render on both the server and in the client, you need to build in a check to see where you are, and handle that accordingly.

You can use this snippet for the detection of where you are:

var canUseDOM = !!(
  typeof window !== 'undefined' &&
  window.document &&
  window.document.createElement
)

Use it to check if you are running server-side or client-side. In your case I would do the following:

  1. If you're server-side you can check the cookies in the HTTP request itself;
  2. If you're client-side you can check your localStorage store instead.

Of course, you can always opt to server-side render your website as an anonymous not authorised user by default. But that would cause the front-end to blink in and out of authorised state and would be annoying for the user.

In your case, I'd try to find authorisation cookies from the actual cookies that are present in your HTTP request.