Activities

webcoderkz

webcoderkz posted a new question

apollo-module •

Is there a way to use this plugin with nuxt-property-decorator?

Is there any examples on how to use nuxt-property-decorator with nuxt-apollo together? Seems like nuxt-apollo doesn't support typescript.

quangvision

quangvision posted a new question

apollo-module •

How to add to req headers XSRF-TOKEN on NuxtServerInit?

I am using Laravel Sanctum to authenticate SPA users. Sanctum set an XSRF-TOKEN to users' cookies and requires that token to pass along with every request.
I can put to headers X-XSRF-TOKEN on client but don't know how to put it into process.server and nuxtServerInit to be specific.
Without setting X-XSRF-TOKEN to request headers, I always get 401 Unauthenticated error.
Hopefully someone could give me some ideas.

bitforcesrl

bitforcesrl posted a new question

apollo-module •

How to keep auth keys secret ?

Hi all,

I'm working with nuxt + apollo + shopify graphQl

Shopify return SEO product details only using the Admin api which is not public and requires a secret token.
This should be fine since i need SEO details only on the server side.
To use both public and private shopify api's i've created two connectors one public and one private (no problem on doing this)

the admin connector looks like this one

ssr = true, ----> this means also for BE not exclusively for BE so the token is still public
httpLinkOptions: {
          // credentials: 'same-origin'
          headers: {
            "Content-Type": "application/json",
            "X-Shopify-Access-Token": process.env.SHOPIFY_ADMIN_API_TOKEN
          }
        },

as you can see i need a token and this will be set in the node ENV.
on localhost i use the module ["@nuxtjs/dotenv", { only: ["PUBLICDOTENV"] }], and with the flag only i can prevent that the secret token will be exposed to the app in the env prop

The problem is that apollo / nuxt, to being able to create the admin connector (fetchable also at runtime) are building the app hardcoding the secret token. this means that is not secure!
I'd like to find a way to being able to do query in the components like this (or via smart query)

let client = context.app.apolloProvider.adminClient;
client.doQuery...

but those query should run only on the server side and the code for that connector should not reach the front end code

I've found a solution now but is not good: I'm passing the data that comes from a secure endpoint in the generate phase. But i'm not able to run custom query on single components. I should pass everything in the generate payload prop which is impossible.

Any ideas?

Thanks a lot

routes: function() {
      const uri =
        "https://xxx.myshopify.com/admin/api/2020-04/graphql.json";
      const query = `query    {
        products(first:100)    {
            edges    {
                node    {
                    handle
                    seo {
                      title
                      description
                    }
                }
            }
        }
      }`;

      return fetch(uri, {
        method: "POST",
        headers: {
          "Content-Type": "application/graphql",
          "X-Shopify-Access-Token": "token"
        },
        body: query
      })
        .then(r => r.json())
        .then(response =>
          response.data.products.edges.map(product => {
            return {
              route: `/products/${product.node.handle}`,
              payload: { seo: product.node.seo }
            };
          })
        )
        .catch(e => console.log(e));
amalhao

amalhao posted a new bug report

apollo-module •

bug Nuxt app compilation error after adding @nuxt/apollo module

Version

v4.0.0-rc.19

Reproduction link

https://codesandbox.io/s/amazing-water-o1ix1

Steps to reproduce

  1. yarn create nuxt-app my-app

create-nuxt-app v2.15.0
✨ Generating Nuxt.js project in my-app
? Project name my-app
? Project description My great Nuxt.js project
? Author name amalhao
? Choose programming language JavaScript
? Choose the package manager Yarn
? Choose UI framework None
? Choose custom server framework None (Recommended)
? Choose Nuxt.js modules (Press <space> to select, to toggle all, to inv
ert selection)
? Choose linting tools (Press <space> to select,
to toggle all, to inver
t selection)
? Choose test framework None
? Choose rendering mode Universal (SSR)
? Choose development tools (Press <space> to select,
to toggle all, to i
nvert selection)

  1. yarn add @nuxtjs/apollo

  2. yarn build

What is expected ?

To not have build errors

What is actually happening?

│ ✖ Nuxt Fatal Error │
│ │
│ Error: Nuxt build error

Diizzayy

Diizzayy posted a new question

apollo-module •

How to reinitiate apollo client and add auth header to subsequent requests after login

My backend generates a httpOnly session cookie that will then be used for authorization by clients to the graphql backend.

The problem that I've ran into is that the page needs to be fully reloaded after the auth state changes (login / logout), The authorization header is only added to the requests after reloading the page (Apollo basically needs to be reinitialized)

Problems:

  • On Login => httpOnly Cookie is set => Apollo is unable to reinitialize and apply auth header
  • On Logout => httpOnly Cookie is cleared => Apollo still applies said revoked token to subsequent requests

Questions:

  • Is there a way to manually reinitialize an apollo client?

My Setup:
Within nuxtServerInit the session cookie is retrieved from the request object and saved in vuex for use in apollo.config.js on the client side

Within the apollo.config.js the session cookie is retrieved from either the request object ( for server side ) or vuex ( for client side ) and added to the apollo headers via httpLinkOptions

apollo.config.js

export default function ({ app, req, env }) {
  const token = () => {
    if (process.server && req.cookies) {
      return req.cookies['__session']
    } else if (!process.server && app.store.getters['user/getToken']) {
      return app.store.getters['user/getToken']
    }
  }

  return {
    httpEndpoint: isDev ? env.urlDev : env.urlProd,

    httpLinkOptions: {
      ...(token() && {
        headers: {
          authorization: `Bearer ${token()}`,
        },
      }),
    },
  }
}
jasonday

jasonday posted a new question

apollo-module •

Nuxt link failing with graphQL (apollo)

There appears to be an issue with my graphQL query, as the template renders but the nuxt-link fails. It just shows the catrule.ruleid text, but is not in a link format.

Template:

<li v-for="catrule in cat_rulesetCollection">
    <nuxt-link :to="`/cat-rule/` + catrule.ruleid">{{ catrule.ruleid }}</nuxt-link>
</li>

Apollo:

import gql from 'graphql-tag'
export default {
    apollo: {
        cat_rulesetCollection: gql` {
            cat_rulesetCollection(populate:1) {
                ruleid
                }
            }`
        }
    }

Error:

Uncaught TypeError: Failed to execute 'observe' on 'IntersectionObserver': parameter 1 is not of type 'Element'.
    at VueComponent.observe (nuxt-link.client.js?4e55:62)
pfritsch

pfritsch posted a new bug report

apollo-module •

bug Nuxt fails to start when adding the package

Version

v4.0.0-rc.19

Reproduction link

https://codesandbox.io/s/sweet-blackwell-y4nuz?file=/package.json

Steps to reproduce

yarn add @nuxtjs/apollo
yarn dev

What is expected ?

Nuxt (Nuxt.js v2.12.2) should start as usual

What is actually happening?

Terminal returns :

 ERROR  Failed to compile with 42 errors

These dependencies were not found:

* core-js/modules/es6.array.find in ./.nuxt/client.js, ./node_module [...]

To install them, you can run: npm install --save core-js/modules/es6.array.find  [...]
koresar

koresar posted a new question

apollo-module •

How to reuse cache between server side page renders?

We have many pages which are very similar, they are based on the same data. When Nuxt renders each page it creates a new instance of ApolloClient (and InMemoryCache).

Looks like there is no way to reuse cache between two different server side renders. We tried everything out there we could find on the internet.

How to reuse cache between requests on the server?

Tinoooo

Tinoooo posted a new feature request

apollo-module •

idea Allow omitting the token in the parameters of $apolloHelpers.onLogin

What problem does this feature solve?

In case the authentication is done via a HttpOnly cookie, there is no need to store the token in a seperate cookie. A current workaround is, to just pass a dummy token.

What does the proposed changes look like?

It should be possible to call $apolloHelpers.onLogin without the first parameter (the token).

drewbaker

drewbaker posted a new feature request

apollo-module •

idea Support for Nuxt new fetch()?

What problem does this feature solve?

It would be great if this could use the new Nuxt fetch() API so that smart queries would be SSR'd at all component levels (not just on Pages like it does currently).

What does the proposed changes look like?

I imagine that you'd want to make this use the new fetch() be default as it doesn't have any breaking changes. Perhaps you'd have a config option to use the old way for people upgrading Nuxt-Apollo for other needs.

xeno

xeno posted a new question

apollo-module •

Property '$apollo' does not exist on type 'CombinedVueInstance<Vue...

I'm running into an issue on a pretty barebones install of Nuxt with @nuxtjs/apollo with Typescript.

In my component, I'm simply trying to access this.$apollo and I'm receiving the following error from Typescript/Vetur:

Property '$apollo' does not exist on type 'CombinedVueInstance<Vue, { form: { user: string; password: string; }; }, { handleSubmit(e: any): void; }, unknown, Readonly<Record<never, any>>>'.Vetur(2339)

My package.json is as follows:

{
  "name": "research-vue",
  "version": "1.0.0",
  "description": "Nuxt Apollo POC",
  "author": "JT",
  "private": true,
  "scripts": {
    "dev": "nuxt",
    "build": "nuxt build",
    "start": "nuxt start",
    "generate": "nuxt generate",
    "test": "jest"
  },
  "dependencies": {
    "@nuxtjs/apollo": "^4.0.0-rc19",
    "@nuxtjs/axios": "^5.3.6",
    "@nuxtjs/dotenv": "^1.4.0",
    "@nuxtjs/pwa": "^3.0.0-0",
    "ant-design-vue": "^1.1.10",
    "graphql-tag": "^2.10.3",
    "nuxt": "^2.0.0",
    "vuex-persistedstate": "^3.0.1"
  },
  "devDependencies": {
    "@nuxt/typescript-build": "^0.6.0",
    "@vue/test-utils": "^1.0.0-beta.27",
    "babel-jest": "^24.1.0",
    "eslint-config-prettier": "^6.10.0",
    "eslint-plugin-prettier": "^3.1.2",
    "jest": "^24.1.0",
    "less": "^3.11.1",
    "less-loader": "^5.0.0",
    "prettier": "^1.19.1",
    "ts-jest": "^25.0.0",
    "vue-jest": "^4.0.0-0"
  }
}

And my nuxt.config.js (the relevant area) looks like this:

 modules: [
    '@nuxtjs/axios',
    '@nuxtjs/pwa',
    '@nuxtjs/dotenv',
    '@nuxtjs/apollo'
  ],
  apollo: {
    clientConfigs: {
      default: {
        httpEndpoint: process.env.GRAPH_URL || 'http://localhost:4000/graphql'
      }
    }
  },

And finally, my component looks like this:

export default Vue.extend({
  components: {},
  data() {
    return {
      form: {
        user: '',
        password: ''
      }
    };
  },
  methods: {
    handleSubmit(e: any) {
      console.log(this.form);

      const client = this.$apollo.getClient();
    }
  }
});

I've googled like crazy, added vue-apollo/types to my tsconfig.json.. nothing seems to be working. Did I do something wrong? Or is this a legit bug? I followed the documentation pretty exact.

Thanks!

ljanecek

ljanecek posted a new question

apollo-module •

nuxt-i18n is not in apollo query context and switchLanguage is not effect for refetch data

Hello, i have multi language application with graphql and im not sure, how i can solved problem, with switching language.

Im using the header of gql server request Content-language for loading correct language.

My apollo-module configuration in nuxt.config.js is:

export default {
  defaultOptions: {
    $query: {
      loadingKey: 'loading',
      fetchPolicy: 'network-only',
    },
  },
  errorHandler: '~/scripts/apollo-error-handler.js',
  clientConfigs: {
    default: '~/scripts/apollo-config.js',
  },
}

apoll-config.js is:

export default (context) => {
  const lang = (context.app.i18n && context.app.i18n.locale) || 'fr'
  return {
    httpEndpoint: process.env.BASE_URL || 'https://loremipsum.com',
    httpLinkOptions: {
      headers: {
        'Content-Language': lang,
      },
    },
  }
}

But, there is 2 issue.

  1. the i18n is not available in the context, but should be
  2. calling this configuration is only by server side request, so when i use switchLocalePath, and route was changed by client side, the header is still same.

Thank you for your help!

drewbaker

drewbaker posted a new feature request

apollo-module •

idea wssLinkOptions for subscriptions?

What problem does this feature solve?

Currently we have httpLinkOptions but we don't have the same options for the a wsLink setup.

What does the proposed changes look like?

Would be great f my config could look like this:

clientConfigs: {
    default: {
        wsEndpoint: "wss://localhost:4000",
        wsLinkOptions: {
            reconnect: true,
            lazy: true,
            connectionParams() {
                workspaceId: "",
                token: ""
            }
        }
    }
}
gibkigonzo

gibkigonzo posted a new question

apollo-module •

setting custom http link

Hello, I'm trying to use custom http link and I get error.
Here is my config:

  apollo: {
    clientConfigs: {
      default: {
        httpEndpoint: 'https://some-test-uri.prismic.io/graphql',
        link: PrismicLink({
          uri: 'https://some-test-uri.prismic.io/graphql',
        }),
        defaultHttpLink: false
      }
    }
  },

Error: Cannot read property 'length' of undefined

    }
    return LinkError;
}(Error));
exports.LinkError = LinkError;
function isTerminating(link) {
    return link.request.length <= 1; // here is error
}
exports.isTerminating = isTerminating;
function toPromise(observable) {
    var completed = false;
    return new Promise(function (resolve, reject) {

PrismicLink returns proper format (I guess):

ApolloLink {
  request: [Function]
}

What I'm doing wrong?

vana-dev

vana-dev posted a new bug report

apollo-module •

bug nuxtServerInit error

Version

v4.0.0-rc.19

Steps to reproduce

I don't know what is wrong :/ I tried to get data in nuxtServerInit

this is my store/index.js

import headerMenuGql from "~/gql/headerMenu.gql";

export const state = () => ({
  headerMenu: null
})

export const mutations = {
  setHeaderMenu (state, data) {
    state.headerMenu = data
  },
}

export const actions = {
  async nuxtServerInit({ dispatch }) {
    await dispatch('getHeaderMenu')
  },
  async getHeaderMenu ({ commit }) {
    const response = await this.app.apolloProvider.defaultClient.query({query: headerMenuGql})
    commit('setHeaderMenu', response)
  }
}

and headerMenu.gql

query headerMenu {
  menus {
    nodes {
      name
      slug
      menuItems {
        nodes {
          childItems {
            nodes {
              menuItemId
              label
              url
            }
          }
          menuItemId
          label
          url
        }
      }
      menuId
    }
  }
}

What is expected ?

get data into vuex store

What is actually happening?

GraphQL error: Internal server error

lsliwaradioluz

lsliwaradioluz posted a new question

apollo-module •

How to use smart queries and mimic behaviour of asyncData?

I dug through all issues regarding smart queries and their cooperation (or lack thereof) with server-side-rendering but none of the answers provided really hits the mark.

In my SSR Nuxt app, I need to fetch some data from an external API created with Strapi. If I understood correctly, this can be achieved in two ways:

  • either using the asyncData method and calling client.query in it
  • or using Apollo's Smart Query declared in the apollo definition

The former works like a charm. When you navigate to the next page using <nuxt-link>, the router waits for the asyncData to load everything and only when the data is ready, it loads that next page. Hence the white progress bar on top of the screen:

https://www.loom.com/share/4513b5ff0b6e40e6bc220364fc190c1c

However, the problem with this solution is that the query run from asyncData does not update automatically when I commit a mutation and the cache changes. That's why I turned to using Smart Queries which cause no such problems.

Unfortunately, those Smart Queries do not seem to be suited for SSR at all. After navigating to a page that uses one of them, my app throws an error (Cannot read property 'length' of undefined). I know, Smart Query is executed on the client so I used v-if="!$apollo.loading" on the root element in template and the error is gone. However, right now I can observe another strange behaviour after navigating to the next page using <nuxt-link>:

https://www.loom.com/share/6d403cc0a1a5485ca48dee1177b29405

The next page gets loaded but is empty (due to v-if used on root element in template). The content appears after a while, once the SmartQuery is completed.

  • is there any way to make router wait for the result of SmartQuery once we hit nuxt-link? Just like it happens in case of using asyncData? This question has already been asked in #278 but no one answered
  • if not, is there any other way to make Smart Query behave like asyncData? Or maybe we could use both - asyncData to fetch data initially and then Smart Query to watch for cache changes and update component accordingly? Or maybe we should use asyncData but instead of client.query use client.watchQuery? I tried this one but could not make watchQuery fetch Data on initial load - just like regular query does
  • if none of the above, what could we do to improve UX and get rid of that blank page for 1-2 seconds? Load some placeholders like faded rectangles ? Or maybe create some custom progress bar?

Thank you in advance,
Łukasz

Billybobbonnet

Billybobbonnet posted a new feature request

apollo-module •

idea Use Apollo Nuxt Module with AWS Amplify (appsync) API

What problem does this feature solve?

I tried to stick with this module when working with a GraphQL AWS API. I couldn't configure how to attach to the request headers the requested API key.

When "edit and resend" the request to add ''x-api-key" as key with the related key as value, it works. See https://stackoverflow.com/q/60816883/3793161

What does the proposed changes look like?

If it is already possible, it's a feature request for the readme. If not, it does not look like a big leap to allow the addition of custom headers for cases like this.

lennartkerkvliet

lennartkerkvliet posted a new question

apollo-module •

Error handling not using Observable

I'm trying to write code for error handling so that I could use JWT refresh tokens. The docs/README provide this example for error handling.

// plugins/apollo-error-handler.js
export default ({ graphQLErrors, networkError, operation, forward }, nuxtContext) => {
  console.log('Global error handler')
  console.log(graphQLErrors, networkError, operation, forward)
}

What I would expect is that I could use operation and forward to write return forward(operation) to retry a failed request, but unfortunately both are undefined. I would also expect that as for example the docs for the apollo-link-error show, you could return an Observable (from "apollo-link") so that you would be able to retry a request. Creating a new Observable will also not result in anything

This is the code I have written:

import { Observable } from 'apollo-link'

export default ({ graphQLErrors, networkError, operation, forward }, nuxtContext) => {
    if (graphQLErrors) {
        for (let err of graphQLErrors) {
            switch (err.extensions.code) {
                case 'UNAUTHENTICATED':
                    return new Observable(subscriber => {

                        nuxtContext.store.dispatch('refresh').then(() => {
                            if (subscriber.closed) return;

                            return forward(operation)subscribe(subscriber);
                        }).catch(error => {
                            subscriber.error(error)
                        })
                    })
            }
        }
    }
};

Everything contained inside Observable is never executed and operation and forward are undefined. Is this a bug? And if it is not, are there any workarounds?

lopermo

lopermo posted a new bug report

apollo-module •

bug Custom error handling not firing

Version

v4.0.0-rc.19

Reproduction link

https://jsfiddle.net/

Steps to reproduce

Add option to nuxt.config.js -> errorHandler: '~/plugins/apollo-error-handler.js',
Create file and print error.

What is expected ?

It should print errors on the console

What is actually happening?

It doesn't print anything when an error happens.

Additional comments?

I'm trying to catch errors when the connection to the server is lost and there's a subscription ongoing. But I can't even catch and log when the server isn't connected and I try to run a query. It's like if the file in "errorHandler" option is ignored.

humiyan02

humiyan02 posted a new question

apollo-module •

onLogin error with Cognito

I used ID token of Cognito user in onLogin method.

      await this.$apolloHelpers.onLogin(state.user.signInUserSession.idToken.jwtToken, undefined, {
        expires: 7,
        path: '/'
      })

But error occurred bellow.
Error on cache reset (setToken) Network error: Response not successful: Received status code 401

When I try putting ID token into getAuth in plugin, It success.

  return {
    httpEndpoint:
      'https://aaaaaaaaaaaaaaaaaa.appsync-api.ap-northeast-1.amazonaws.com/graphql',
    getAuth: () => idToken
  }
}