Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Server Side Rendering window is not defined. #82

Closed
qk0106 opened this issue Mar 28, 2018 · 10 comments · Fixed by #137
Closed

Server Side Rendering window is not defined. #82

qk0106 opened this issue Mar 28, 2018 · 10 comments · Fixed by #137
Labels
enhancement Used for enhancements to AppSync SDK

Comments

@qk0106
Copy link

qk0106 commented Mar 28, 2018

There are only some options left for us:

  • Give up SSR (We want to keep it).
  • Use pure apollo client and regex match localStorage to get the token, which is stored by aws-amplify and cognito authentication (This is risky).
  • Mock an incomplete window in advance. (Well, incomplete..)

We don't want to do things that would risk too much. Could you please do something about it?

`ReferenceError: window is not defined

ReferenceError: window is not defined

at Object.<anonymous> (/Users/.../node_modules/paho-client/src/mqttws31.js:2143:4)

at Module._compile (module.js:660:30)

at Module._extensions..js (module.js:671:10)

at Object.require.extensions.(anonymous function) [as .js] (/Users/.../node_modules/babel-register/lib/node.js:152:7)

at Module.load (module.js:573:32)

at tryModuleLoad (module.js:513:12)

at Function.Module._load (module.js:505:3)

at Module.require (module.js:604:17)

at require (internal/module.js:11:18)

at Object.<anonymous> (/Users/.../node_modules/aws-appsync/lib/link/subscription-handshake-link.js:30:12)`
@powerful23 powerful23 added the enhancement Used for enhancements to AppSync SDK label Apr 2, 2018
@nicholas-gates
Copy link

Same problem here using AppSync with a next.js project.

@nodkrot
Copy link

nodkrot commented Apr 15, 2018

🤦‍♂️ how can I just use regular Apollo Client with api key?

@marcspicer1
Copy link

marcspicer1 commented Apr 19, 2018

same issue, using the appsync in reactql project.Its working fine(i'm able to get the data using aws-appsync ) but as soon as I import 'aws-appsync' in my project I get the refrence error "window is not defined" looks like 'aws-appsync' is referencing the browser's window object, even if it is only imported, before any usage.

@qk0106
Copy link
Author

qk0106 commented Apr 27, 2018

Not sure is this fix working well.. #110
Can some author or contributor have a look at it?

@tgorka
Copy link
Contributor

tgorka commented Apr 27, 2018

@qk0106 Normally I had the same error (but I didn't do SSR) and I made the #110. You can make workaround before reviewing my pull request by adding:
import "node-window-polyfill/register"
before importing aws-appsync to see if it's fixing the problem

@rohanray
Copy link

@qk0106 @tgorka node-window-polyfill/register has incomplete window object. I'm using next.js. It breaks on window.location.href with the error href is undefined

@maziarz
Copy link

maziarz commented Apr 29, 2018

Having the same issue with Nuxt.js

@tgorka
Copy link
Contributor

tgorka commented Apr 29, 2018

do you know how to get current href in this frameworks on the server site?

@manueliglesias
Copy link
Contributor

Hi!

We are actively working on removing dependencies on the window object to enable server side rendering without having to polyfill stuff. Stay tuned.

If you're curious how this would work in the future (please understand this is experimental and requires for now unpublished modules and unmerged pull requests to third party repos), you can take a look at manueliglesias/urban-pancake (a nextjs web app I am using to test stuff), specifically this piece https://github.com/manueliglesias/urban-pancake/blob/61f167f99793d6573adcf577d975578353d5b70c/lib/initApollo.js#L13-L31

@rohanray
Copy link

rohanray commented May 2, 2018

@manueliglesias this sounds great :) currently I have implemented https://github.com/zeit/next.js/#custom-app i.e. I have over-ridden _app.js as below:


import App, { Container } from "next/app";
import React from "react";
import { ApolloProvider } from "react-apollo";
// import { Rehydrated } from "aws-appsync-react";

export default class MyApp extends App {
  render() {
    const { Component, pageProps } = this.props;
    if (process.browser) {
      const AWSAppSyncClient = require("aws-appsync").default;
      this.client = new AWSAppSyncClient({
        url:
          "https://XXX.appsync-api.us-east-1.amazonaws.com/graphql",
        region: "us-east-1",
        auth: {
          type: "API_KEY",
          apiKey: "da2-XXX"
        },
        disableOffline: true,
        complexObjectsCredentials: () => {
          return new AWS.Credentials({
            accessKeyId: "XXX",
            secretAccessKey: "XXX"
          });
        }
      });
      return (
        <ApolloProvider client={this.client}>
          {/* <Rehydrated> */}
          <Container>
            <Component {...pageProps} />
          </Container>
          {/* </Rehydrated> */}
        </ApolloProvider>
      );
    } else {
      return <div>Loading</div>
    }
  }
}

We could at least get Appsync working with Next.js. However, by above solution we have lost actual SSR capabilities.

I must say that Appsync is really great. We have been using it to build a B2B SaaS solution since its preview days :) If Appsync library does remove all dependencies from window and browser objects and also support SSR libraries;,it would be happy days for us :)

timneutkens pushed a commit to vercel/next.js that referenced this issue Jun 29, 2018
I had some trouble to get server side rendering with the AWSAppSyncClient working. I finally found a solution in awslabs/aws-mobile-appsync-sdk-js#82 but it might be worth to share it here as well. Instead of adding a big code block to each file I'll just refer to this Pull Request.

______

In case you want to use the `AWSAppSyncClient` you just need to replace the `create()` function with this function:
```jsx
import AWSAppSyncClient from 'aws-appsync';
import { AUTH_TYPE } from 'aws-appsync/lib/link/auth-link';

function create(initialState) {
  const client = new AWSAppSyncClient({
    url: AWS_AppSync.graphqlEndpoint,
    region: AWS_AppSync.region,
    auth: {
      type: AUTH_TYPE.API_KEY,
      apiKey: AWS_AppSync.apiKey,

      // Amazon Cognito Federated Identities using AWS Amplify
      //credentials: () => Auth.currentCredentials(),

      // Amazon Cognito user pools using AWS Amplify
      // type: AUTH_TYPE.AMAZON_COGNITO_USER_POOLS,
      // jwtToken: async () => (await Auth.currentSession()).getIdToken().getJwtToken(),
    },
    disableOffline: true,
  }, {
    cache: new InMemoryCache().restore(initialState || {}),
    ssrMode: true
  });

  return client;
}
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement Used for enhancements to AppSync SDK
Projects
None yet
Development

Successfully merging a pull request may close this issue.

9 participants