Activities

suenot

suenot posted a new question

apollo-module •

loading is not defined

In plugins/apollo-watch-loading-handler.js

export default (isLoading, countModifier, nuxtContext) => {
  loading += countModifier
  console.log('Global loading', loading, countModifier)
}

My nuxt.config:

// import colors from 'vuetify/es5/util/colors'

export default {
  mode: 'universal',
  /*
  ** Headers of the page
  */
  head: {
    titleTemplate: '%s - ' + process.env.npm_package_name,
    title: process.env.npm_package_name || '',
    meta: [
      { charset: 'utf-8' },
      { name: 'viewport', content: 'width=device-width, initial-scale=1' },
      { hid: 'description', name: 'description', content: process.env.npm_package_description || '' }
    ],
    link: [
      { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }
    ]
  },
  /*
  ** Customize the progress-bar color
  */
  loading: { color: '#fff' },
  /*
  ** Global CSS
  */
  css: [
  ],
  /*
  ** Plugins to load before mounting the App
  */
  plugins: [
    { src : '~/plugins/vue-apexchart.js', ssr : false },
    { src : '~/plugins/v-charts.js', ssr : false },
  ],
  /*
  ** Nuxt.js dev-modules
  */
  buildModules: [
    '@nuxtjs/vuetify',
  ],
  /*
  ** Nuxt.js modules
  */
  modules: [
    '@nuxtjs/axios',
    '@nuxtjs/auth',
    '@nuxtjs/apollo'
  ],
  /*
  ** vuetify module configuration
  ** https://github.com/nuxt-community/vuetify-module
  */
  vuetify: {
    customVariables: ['~/assets/variables.scss'],
    theme: {
      dark: true,
      themes: {
        // dark: {
        //   primary: colors.blue.darken2,
        //   accent: colors.grey.darken3,
        //   secondary: colors.amber.darken3,
        //   info: colors.teal.lighten1,
        //   warning: colors.amber.base,
        //   error: colors.deepOrange.accent4,
        //   success: colors.green.accent3
        // }
      }
    }
  },
  /*
  ** Build configuration
  */

  build: {
    // vendor : ['vue-apexchart'],
    /*
    ** You can extend webpack config here
    */
    extend (config, ctx) {
    }
  },
  serverMiddleware: ['./auth'],
  axios: {
    proxy: true
  },
  proxy: {
    '/api': 'http://localhost:3000'
  },
  auth: {
    redirect: {
      callback: '/callback'
    },
    strategies: {
      auth0: {
        domain: 'suenot.eu.auth0.com',
        client_id: 'NkwwJnyxYqp5uTifYg_LCqBiQ6SWWMyo'
      },
    }
  },
  apollo: {
    tokenName: 'apollo-token', // optional, default: apollo-token
    cookieAttributes: {
      /**
        * Define when the cookie will be removed. Value can be a Number
        * which will be interpreted as days from time of creation or a
        * Date instance. If omitted, the cookie becomes a session cookie.
        */
      expires: 7, // optional, default: 7 (days)

      /**
        * Define the path where the cookie is available. Defaults to '/'
        */
      path: '/', // optional
      /**
        * Define the domain where the cookie is available. Defaults to
        * the domain of the page where the cookie was created.
        */
      domain: 'http://localhost:3000/', // optional

      /**
        * A Boolean indicating if the cookie transmission requires a
        * secure protocol (https). Defaults to false.
        */
      secure: false,
    },
    includeNodeModules: true, // optional, default: false (this includes graphql-tag for node_modules folder)
    authenticationType: 'Basic', // 'Basic', // optional, default: 'Bearer'
    // (Optional) Default 'apollo' definition
    defaultOptions: {
      // See 'apollo' definition
      // For example: default query options
      $query: {
        loadingKey: 'loading',
        fetchPolicy: 'cache-and-network',
      },
    },
    // optional
    watchLoading: '~/plugins/apollo-watch-loading-handler.js',
    // optional
    errorHandler: '~/plugins/apollo-error-handler.js',
    // required
    clientConfigs: {
      default: {
        // required
        httpEndpoint: 'https://suenot-hasura.herokuapp.com/v1/graphql',
        // optional
        // override HTTP endpoint in browser only
        browserHttpEndpoint: '/graphql',
        // optional
        // See https://www.apollographql.com/docs/link/links/http.html#options
        httpLinkOptions: {
          credentials: 'same-origin'
        },
        // You can use `wss` for secure connection (recommended in production)
        // Use `null` to disable subscriptions
        // wsEndpoint: 'wss://suenot-hasura.herokuapp.com/v1/graphql', // optional
        // LocalStorage token
        // tokenName: 'auth._token.auth0', // optional
        // Enable Automatic Query persisting with Apollo Engine
        persisting: false, // Optional
        // Use websockets for everything (no HTTP)
        // You need to pass a `wsEndpoint` for this to work
        websocketsOnly: false // Optional
      },
      // test: {
      //   httpEndpoint: 'http://localhost:5000',
      //   wsEndpoint: 'ws://localhost:5000',
      //   tokenName: 'apollo-token'
      // },
      // alternative: user path to config which returns exact same config options
      // test2: '~/plugins/my-alternative-apollo-config.js'
    }
  }
}
kapilgohil

kapilgohil posted a new question

apollo-module •

Apollo or Axios

Hi All,

So I am currently using Apollo to query an external graphql endpoint (Shopify storefront API)

Should I be using Apollo or Axios?
What are the differences?

Thanks

kapilgohil

kapilgohil posted a new question

apollo-module •

Apollo link state or vuex

Hi All,

So I am implementing a login form.
I know that I need to have some sort of state management, i.e. storing a user access token etc.
What is the difference in using apollo link state to vuex?

Thanks

drewbaker

drewbaker posted a new question

apollo-module •

How to get cookies working on SSR correctly?

We've built a framework around Nuxt to get it to work with WordPress really well. We have been pulling our hair out trying to get post previewing working.

A common setup will be a WordPress install running on a domain like http://api.example.com and then to have Nuxt running on http://www.example.com. There is a WordPress plugin called WP-Graph-QL that creates a GraphQL endpoint like http://api.example.com/graphql, and we wrote a CORS plugin to set the correct CORS headers to work with whatever the frontend origin may be. This is that plugin if you are curious https://github.com/funkhaus/wp-graphql-cors

Our Nuxt Apollo setup is this:

export default function() {
    return {
        httpEndpoint: process.env.DEFAULT_ENDPOINT,
        getAuth: () => process.env.BASIC_API_TOKEN || "",
        httpLinkOptions: {
            credentials: "include"
        }
    }
}

FYI sometimes the API will be hidden behind a Basic Auth UN/PW (like when on a staging site for example), that is what the getAuth function is doing.

This all seems to work client side, but it fails on SSR for some reason. It seems the cookies don't get sent in the SSR request, but they do in the client side request. Am I missing something super obvious here?

lroy83

lroy83 posted a new question

apollo-module •

Update WebSocketLink header or reset apollo

I'm using nuxt apollo with Hasura.

apollo is being initialized on site first load with current token (passed as header to http and ws links (along with 'x-hasura-role'))
my problem is when the token is being refreshed!

how can i update those headers on WebSocketLink? (i know how to do that with httpLink)
i've tried middleware but they only work for httpLink, not with WebSocketLink - the headers does't change..

or is there a way to reset/reinitiate the apollo instance?

Thanks!

codeofsumit

codeofsumit resolved the question #c282

apollo-module •

How to set Auth Headers

Even though I might be the only one not getting this: in case anyone else has problems authenticating, the httpLinkOptions allow you to add a header.

apollo: {
    clientConfigs: {
      default: {
        // required  
        httpEndpoint: 'https://graphql.fauna.com/graphql',
        httpLinkOptions: {
          headers: {
            Authorization: 'Bearer <yourToken>'
          }
        }
      }
    }
  },

Docs: https://www.apollographql.com/docs/link/links/http/#options

codeofsumit

codeofsumit posted a new question

apollo-module •

How to set Auth Headers

Hi all, I'm a complete beginner with GraphQL and Apollo and I wanted to get a simple quick and dirty test up and running with nuxt and FaunaDB.
Unfortunately, I'm stuck since 2 hours because I can't figure out how to add the authorization token to the nuxt-apollo module. No cookies, no localStorage, just a plain old string, hard coded.

NuxtJS Config:

// nuxt.config.js
apollo: {
    clientConfigs: {
      default: {
        httpEndpoint: 'https://graphql.fauna.com/graphql',
      }
    }
  },

I've also added a plugin as from the docs it looks like I'm able to add a token there:

// /plugins/apollo/config.js
export default function (context) {
  return {
    httpEndpoint: 'https://google.com/graphql',
    getAuth: () => 'Bearer myFaunaDBToken'
  }
}

// nuxt.config.js
plugins: ['~/plugins/apollo/config.js'],

But that did not change the endpoint nor did it add a token.

Can anyone push me into the right direction? Thanks a lot in advance and thanks for your work on Open Source 👏👏

mromanoff

mromanoff posted a new bug report

apollo-module •

bug Apollo 'fixture-local-state' example trying to connect to server. http://localhost:3000/graphql

Version

v4.0.0-rc.19

Reproduction link

http://localhost:3000

Steps to reproduce

clone project. run npm run dev4 open dev tools -> network tab. Notice error index.js?cf67:111 POST http://localhost:3000/graphql 404 (Not Found)

What is expected ?

Network request should not be initiated. should not be called

What is actually happening?

Error 404: http://localhost:3000/graphql

Jesus82

Jesus82 posted a new question

apollo-module •

Reduce bundle size

Is there any way to reduce bundle size? I'm just using smart queries, no vue-apollo components.

This was also proposed and implemented in vue-apollo https://github.com/vuejs/vue-apollo/issues/660

fabiomiguelmfernandes

fabiomiguelmfernandes posted a new question

apollo-module •

[Apollo module] errorHandler should be a path to an exported error handler config.

Hello guys,

after installing ubuntu on my machine, my project stoped compiling. Before i was on zorin then after changing to ubuntu this project no longer works.

If i remove the errorHandler from nuxt config it gives eslint error (before this never happend).

Has someone fix this?

argueta15

argueta15 posted a new question

apollo-module •

TypeError: Cannot read property 'defaultClient' of undefined

I generate static project and deploy in amazon s3, when refresh page I get error:

TypeError: Cannot read property 'defaultClient' of undefined

If my project deploy in node sever it work it.

apollo: { clientConfigs: { default: '~/plugins/apollo-config.js' } },

export default function (context) { return { httpEndpoint: process.env.HTTP_ENDPOINT, getAuth: () => { const token = localStorage.getItem('AUTH_TOKEN') if (token) { returnBearer ${token} } else { return '' } } } }

GaborTorma

GaborTorma posted a new feature request

apollo-module •

idea websocketsOnly not always

What problem does this feature solve?

ApolloClient use httpEndpoint before the websocket is not connected.

What does the proposed changes look like?

Please create a force mode for websocketsOnly, thar waits for websocket connection before quering.

pimlie

pimlie posted a new bug report

apollo-module •

bug Package does not get updated past rc9 due to semver mismatch

Version

v4.0.0-rc.19

Reproduction link

https://jubianchi.github.io/semver-check/#/^4.0.0-rc6/4.0.0-rc19

Steps to reproduce

Check the repro link. For the rc versions to work correctly a dot between rc and the number is required.

As the git tags are correctly set with a dot, not sure where in the release process the dot between rc and the number is removed. Maybe you just need to add --prerelease rc when releasing with standard-version?

What is expected ?

rc19 satisfies the rc6 constraint

What is actually happening?

it doesnt

Additional comments?

This issue causes that users will only ever be able to install 4.0.0-rc9 at the most (without manual interaction)

chriscalo

chriscalo posted a new bug report

apollo-module •

bug Empty SSR page content when `pollInterval` is set

Version

v4.0.0-rc.19

Reproduction link

https://github.com/chriscalo/nuxt-apollo-polling

Steps to reproduce

  1. Create Nuxt app (yarn create nuxt-app nuxt-apollo-polling)
  2. Add @nuxtjs/apollo and create basic graphql server
  3. Add graphql query to a .vue page and include a pollInterval

(See the exact steps I've taken in the repro repo commits)

For example, in pages/index.vue:

<script>
import Logo from '~/components/Logo.vue'
import { User } from '~/queries/auth.graphql'

export default {
  apollo: {
    user: {
      query: User,
      prefetch: true,
      // adding this `pollInterval` value causes the problem
      pollInterval: 1000,
    },
  },
  components: {
    Logo
  }
}
</script>

What is expected ?

Adding a pollInterval to an Apollo query works without breaking anything.

What is actually happening?

Adding a pollInterval value causes the server to return empty page content. You can see this by right-clicking the page and selecting View Page Source. All of the Nuxt <scripts> and containing <div>s are there, but the page content is empty.

Here's what I see in the <body> when the pollInterval is present:

    <div data-server-rendered="true" id="__nuxt"><!----><div id="__layout"><div><script>window.__NUXT__={layout:"default",data:[{}],error:null,serverRendered:true,apollo:{defaultClient:Object.create(null)},logs:[]};</script><script src="/_nuxt/runtime.js" defer></script><script src="/_nuxt/pages/index.js" defer></script><script src="/_nuxt/pages/index.a474644729814055f4ea.hot-update.js" defer></script><script src="/_nuxt/commons.app.js" defer></script><script src="/_nuxt/vendors.app.js" defer></script><script src="/_nuxt/app.js" defer></script>

Compare that with what's in the <body> when the pollInterval is removed:

<div data-server-rendered="true" id="__nuxt"><!----><div id="__layout"><div><div class="container"><div><svg width="245" height="180" viewBox="0 0 452 342" xmlns="http://www.w3.org/2000/svg" class="NuxtLogo"><g fill="none" fill-rule="evenodd"><path d="M139 330l-1-2c-2-4-2-8-1-13H29L189 31l67 121 22-16-67-121c-1-2-9-14-22-14-6 0-15 2-22 15L5 303c-1 3-8 16-2 27 4 6 10 12 24 12h136c-14 0-21-6-24-12z" fill="#00C58E"></path> <path d="M447 304L317 70c-2-2-9-15-22-15-6 0-15 3-22 15l-17 28v54l39-67 129 230h-49a23 23 0 0 1-2 14l-1 1c-6 11-21 12-23 12h76c3 0 17-1 24-12 3-5 5-14-2-26z" fill="<a href="https://github.com/undefined/undefined/issues/108775" target="_blank">#108775</a>"></path> <path d="M376 330v-1l1-2c1-4 2-8 1-12l-4-12-102-178-15-27h-1l-15 27-102 178-4 12a24 24 0 0 0 2 15c4 6 10 12 24 12h190c3 0 18-1 25-12zM256 152l93 163H163l93-163z" fill="#2F495E" fill-rule="nonzero"></path></g></svg> <h1 class="title">
      nuxt-apollo-polling
    </h1> <h2 class="subtitle">
      repro for polling bug in @nuxtjs/apollo
    </h2> <p>
      user = [email protected]
    </p> <div class="links"><a href="https://nuxtjs.org/" target="_blank" class="button--green">
        Documentation
      </a> <a href="https://github.com/nuxt/nuxt.js" target="_blank" class="button--grey">
        GitHub
      </a></div></div></div></div></div></div><script>window.__NUXT__={layout:"default",data:[{}],error:null,serverRendered:true,apollo:{defaultClient:Object.create(null,{ROOT_QUERY:{writable:true,enumerable:true,value:{user:"[email protected]"}}})},logs:[]};</script><script src="/_nuxt/runtime.js" defer></script><script src="/_nuxt/pages/index.js" defer></script><script src="/_nuxt/pages/index.8be2ffa62aee797d62e6.hot-update.js" defer></script><script src="/_nuxt/commons.app.js" defer></script><script src="/_nuxt/vendors.app.js" defer></script><script src="/_nuxt/app.js" defer></script>
mromanoff

mromanoff posted a new feature request

apollo-module •

idea Documentation or examples how to use Apollo local state management

What problem does this feature solve?

how to use Apollo local state management? any examples? Let's say I want to create Apollo Local UI Cache State management. I our project we don't use vuex. as described in https://vue-apollo.netlify.com/guide/local-state.html#why-use-apollo-local-state-management

pachiraDIG

pachiraDIG posted a new bug report

apollo-module •

bug JSON.parse: unexpected character at line 1 column 1

Version

v4.0.0-rc.19

Reproduction link

https://github.com/pachiraDIG/hub

Steps to reproduce

Repo

After several hours, I can't seem to pinpoint the cause of this error when running a query.

Config for @nuxt/apollo module:

apollo: {
    includeNodeModules: true,
    clientConfigs: {
      default: {
        httpEndpoint: '~/.netlify/functions/fauna-graphql'
      }
    }
  }

The error is coming through the apollo module:

 var vueApolloOptions = Object.assign(providerOptions, {
    errorHandler: function errorHandler(error) {
      console.log('%cError', 'background: red; color: white; padding: 2px 4px; border-radius: 3px; font-weight: bold;', error.message);
    }
  });

The Netlify Function, taken directly from a Netlify team member's example repo:

const { ApolloServer } = require('apollo-server-lambda')
const { createHttpLink } = require('apollo-link-http')
const fetch = require('node-fetch')
const { introspectSchema, makeRemoteExecutableSchema } = require('graphql-tools')

exports.handler = async function(event, context) {
  /** required for Fauna GraphQL auth */
  if (!process.env.FAUNADB_SERVER_SECRET) {
    const msg = `
    FAUNADB_SERVER_SECRET missing. 
    Did you forget to install the fauna addon or forgot to run inside Netlify Dev?
    `
    console.error(msg)
    return {
      statusCode: 500,
      body: JSON.stringify({ msg })
    }
  }

  const b64encodedSecret = Buffer.from(
    process.env.FAUNADB_SERVER_SECRET + ':' // weird but they
  ).toString('base64')

  const headers = { Authorization: `Basic ${b64encodedSecret}` }

  /** standard creation of apollo-server executable schema */
  const link = createHttpLink({
    uri: 'https://graphql.fauna.com/graphql', // modify as you see fit
    fetch,
    headers
  })

  const schema = await introspectSchema(link);

  const executableSchema = makeRemoteExecutableSchema({
    schema,
    link
  })

  const server = new ApolloServer({
    schema: executableSchema
  })

  return new Promise((yay, nay) => {
    const cb = (err, args) => (err ? nay(err) : yay(args))
    server.createHandler()(event, context, cb)
  })
}

Inside the component: (The faunadb schema is set up exactly from their example tutorial)

export default {
  data() {
    return {
      test: {},
    }
  },
  apollo: {
    test: gql`
      query {
        allWarehouses {
          data {
            _id
            name
            address {
              street
              city
              state
              zipCode
            }
          }
        }
      }
    `
  }
}

From reading similar questions regarding the same error (but not the same stack), it could be related to something trying parse HTML as JSON. I've also seen that it could be solved with JSON.stringify, but I don't know where the hayhay I should apply it.

Any suggestions?

What is expected ?

A clean return

What is actually happening?

Browser console: Error Network error: JSON.parse: unexpected character at line 1 column 1 of the JSON data

pachiraDIG

pachiraDIG posted a new question

apollo-module •

JSON.parse: unexpected character at line 1

Repo

After several hours, I can't seem to pinpoint the cause of this error when running a query. New to GraphQL & Apollo.

Config for @nuxt/apollo module:

apollo: {
    includeNodeModules: true,
    clientConfigs: {
      default: {
        httpEndpoint: '~/.netlify/functions/fauna-graphql'
      }
    }
  }

The error is coming through the apollo module:

 var vueApolloOptions = Object.assign(providerOptions, {
    errorHandler: function errorHandler(error) {
      console.log('%cError', 'background: red; color: white; padding: 2px 4px; border-radius: 3px; font-weight: bold;', error.message);
    }
  });

The Netlify Function, taken directly from a Netlify team member's example repo:

const { ApolloServer } = require('apollo-server-lambda')
const { createHttpLink } = require('apollo-link-http')
const fetch = require('node-fetch')
const { introspectSchema, makeRemoteExecutableSchema } = require('graphql-tools')

exports.handler = async function(event, context) {
  /** required for Fauna GraphQL auth */
  if (!process.env.FAUNADB_SERVER_SECRET) {
    const msg = `
    FAUNADB_SERVER_SECRET missing. 
    Did you forget to install the fauna addon or forgot to run inside Netlify Dev?
    `
    console.error(msg)
    return {
      statusCode: 500,
      body: JSON.stringify({ msg })
    }
  }

  const b64encodedSecret = Buffer.from(
    process.env.FAUNADB_SERVER_SECRET + ':' // weird but they
  ).toString('base64')

  const headers = { Authorization: `Basic ${b64encodedSecret}` }

  /** standard creation of apollo-server executable schema */
  const link = createHttpLink({
    uri: 'https://graphql.fauna.com/graphql', // modify as you see fit
    fetch,
    headers
  })

  const schema = await introspectSchema(link);

  const executableSchema = makeRemoteExecutableSchema({
    schema,
    link
  })

  const server = new ApolloServer({
    schema: executableSchema
  })

  return new Promise((yay, nay) => {
    const cb = (err, args) => (err ? nay(err) : yay(args))
    server.createHandler()(event, context, cb)
  })
}

Inside the component: (The faunadb schema is set up exactly from their example tutorial)

export default {
  data() {
    return {
      test: {},
    }
  },
  apollo: {
    test: gql`
      query {
        allWarehouses {
          data {
            _id
            name
            address {
              street
              city
              state
              zipCode
            }
          }
        }
      }
    `
  }
}

Any suggestions?

look416

look416 posted a new bug report

apollo-module •

bug apollo not initialized under spa mode with redirect

Version

v4.0.0-rc.19

Reproduction link

https://github.com/look416/nuxt-apollo-error-demo

Steps to reproduce

  1. Set the mode to "universal" under nuxt config
  2. import redirect under auth middleware
  3. check apollo token
  4. call redirect function if token not found
  5. yarn generate
  6. check it using simple http server

What is expected ?

  1. The page is rendered successfully

What is actually happening?

  1. Error popping:
    Screenshot 2019-12-19 at 12.01.07 PM.png

Additional comments?

As of now, I am managed to bypass the issue by either two ways:

  1. setting the mode to "spa"
  2. instead of importing redirect, use the app.router to do the redirection
chriscalo

chriscalo posted a new question

apollo-module •

How to prefetch Apollo query before link click

I'd love to get a head start on loading the data (via Apollo query) required for a page before the user clicks a link. (Perhaps on mouseenter or touchstart.)

What's the best mechanism for kicking off all Apollo queries before the user clicks the link to the page that owns/needs those queries?

chriscalo

chriscalo posted a new question

apollo-module •

Recommended way of waiting on an Apollo query before rendering the next page?

When using the Apollo module in a Nuxt app, the default behavior when changing routes is to render the new page immediately, before data has been fetched via Apollo.

This results in some pretty janky rendering experiences where the page does a partial render and very soon after completes rendering with data from the server, making everything on the page shift due to the changing size of components that now have data. This looks pretty bad because the data actually comes back fairly quickly, so it would be fine to wait for the data to return before rendering the new route.

What's the recommended way of waiting on an Apollo query before rendering the next page?

Here's a related question that's not specific to Nuxt, so I'm not sure how to translate the recommendation to a Nuxt app:

https://github.com/vuejs/vue-apollo/issues/598

Might someone be able to provide an example of using beforeRouteEnter to fetch data via Apollo and only render the page once the data is fetched?