title: Laravel lighthouse current user is null via next apollo
body: <p>I have a fresh copy of laravel with sanctum and lighthouse. When I do the login route via axios, everything works as expected. After logging in via axios, I added a <code>lazyquery</code> to attempt to query some guarded fields but I get unauthenticated. I am not sure why and it has been three days I've been dealing with this. I'd really appreciate your help.</p>
  <p>This works</p>
  <pre><code>useEffect(() =&gt; {
      axios.defaults.withCredentials = true;
      // get the token from the server
      axios.get(`http://api.newods.test/sanctum/csrf-cookie`).then(function (resolve){
        // try login with the user
        axios.post('http://api.newods.test/api/login', {
          email: 'test@test.com',
          password: 'test'
        }).then(function (resolve) {
          console.log(`logged in ${resolve.data}`);
          axios
            .get(&quot;http://api.newods.test/api/gated&quot;, { withCredentials: true })
            .then(function (resolve) {
              console.log(`gated ${resolve.data}`);
              axios
                .get(&quot;http://api.newods.test/api/logout&quot;, {
                  withCredentials: true,
                })
                .then(function (resolve) {
                  console.log(`logged out ${resolve.data}`);
                  axios
                    .get(&quot;http://api.newods.test/api/gated&quot;, {
                      withCredentials: true,
                    })
                    .then(function (resolve) {
                      console.log(
                        `trying to get to gated after logging out ${resolve.data}`
                      );
                    });
                });
            });
        });
      });
  
    }, []);
  </code></pre>
  <p>But when I cut it short and change to this, I get unauthenticated</p>
  <pre><code>const HELLO = gql\`
    query hello {
      hello
    }
  `;
  
  
  function Home() {
  
    const [hello, { loading, data }] = useLazyQuery(HELLO);
  
    useEffect(() =&gt; {
      axios.defaults.withCredentials = true;
      // get the token from the server
      axios.get(`http://api.newods.test/sanctum/csrf-cookie`).then(function (resolve){
        // try login with the user
        axios.post('http://api.newods.test/api/login', {
          email: 'test@test.com',
          password: 'test'
        }).then(function (resolve) {
          console.log('logged in');
  
        });
      });
  
    }, []);
  
  
    return (
      &lt;div className=&quot;container&quot;&gt;
        &lt;div&gt;Index&lt;/div&gt;
        &lt;button onClick={() =&gt; hello()}&gt;
          Click to hello world
        &lt;/button&gt;
        &lt;p&gt;{data &amp;&amp; data.hello || ''}&lt;/p&gt;
      &lt;/div&gt;
    );
  }
  
  export default withApollo(Home);
  </code></pre>
  <p>And that returns <code>unauthenticated</code> when I add the <code>@guard</code> directive and I see the token from the axios login request is in the headers... I am not sure what I am missing here I'd greatly appreciate your help.</p>
  <h3>schema.graphql</h3>
  <pre><code>type Query {
      users: [User!]! @paginate(defaultCount: 10)
      user(id: ID @eq): User @find
      hello: String! @guard
      me: User @auth
  }
  </code></pre>
  <h3>.env</h3>
  <pre><code>SESSION_DRIVER=cookie
  SESSION_LIFETIME=120
  SESSION_DOMAIN=.newods.test
  SANCTUM_STATEFUL_DOMAINS=newods.test:3000 
  </code></pre>
  <h3>config/cors.php</h3>
  <pre><code>return [
   
      'paths' =&gt; ['api/*', 'sanctum/csrf-cookie', 'graphql'],
  
      'allowed_methods' =&gt; ['*'],
  
      'allowed_origins' =&gt; ['*'],
  
      'allowed_origins_patterns' =&gt; [],
  
      'allowed_headers' =&gt; ['*'],
  
      'exposed_headers' =&gt; [],
  
      'max_age' =&gt; 0,
  
      'supports_credentials' =&gt; true,
  
  ];
  
  </code></pre>
  <h3>config/lighthouse</h3>
  <pre><code>'route' =&gt; [
          /*
           * The URI the endpoint responds to, e.g. mydomain.com/graphql.
           */
          'uri' =&gt; '/graphql',
  
          /*
           * Lighthouse creates a named route for convenient URL generation and redirects.
           */
          'name' =&gt; 'graphql',
  
          /*
           * Beware that middleware defined here runs before the GraphQL execution phase,
           * make sure to return spec-compliant responses in case an error is thrown.
           */
          'middleware' =&gt; [
              \Nuwave\Lighthouse\Support\Http\Middleware\AcceptJson::class,
  
              // Logs in a user if they are authenticated. In contrast to Laravel's 'auth'
              // middleware, this delegates auth and permission checks to the field level.
              \Nuwave\Lighthouse\Support\Http\Middleware\AttemptAuthentication::class,
          ],
  
          /*
           * The `prefix` and `domain` configuration options are optional.
           */
          //'prefix' =&gt; '',
          //'domain' =&gt; '',
      ],
  </code></pre>
  <p>In my next app with apollo</p>
  <h3>create.js</h3>
  <pre><code>import { ApolloClient } from 'apollo-client';
  import { InMemoryCache } from 'apollo-cache-inmemory';
  import { createHttpLink } from 'apollo-link-http';
  import { setContext } from 'apollo-link-context';
  import Cookies from 'js-cookie';
  import { serverUrl } from '../config';
  
  export default function createApolloClient(initialState, ctx) {
    // The `ctx` (NextPageContext) will only be present on the server.
    // use it to extract auth headers (ctx.req) or similar.
  
    const authLink = setContext((_, { headers  }) =&gt; {
      // get the authentication token from local storage if it exists
      const token = Cookies.get(&quot;XSRF-TOKEN&quot;);
      // console.log(`token is ${token}`);
      // return the headers to the context so httpLink can read them
      return {
        headers: {
          ...headers,
          &quot;Access-Control-Allow-Credentials&quot;: true,
          ...(token ? { authorization: `X-XSRF-TOKEN=${token}` } : {}),
        },
      };
    });
  
    const httpLink = createHttpLink({
      uri: serverUrl,
      credentials: 'same-origin',
    });
  
    return new ApolloClient({
      ssrMode: Boolean(ctx),
      link: authLink.concat(httpLink),
      connectToDevTools: true,
      cache: new InMemoryCache().restore(initialState),
    });
  }
  
  </code></pre>
  <h3>withApollo.js</h3>
  <pre><code>import React from &quot;react&quot;;
  import Head from &quot;next/head&quot;;
  import { ApolloProvider } from &quot;@apollo/react-hooks&quot;;
  import { ApolloClient } from &quot;apollo-client&quot;;
  import { InMemoryCache } from &quot;apollo-cache-inmemory&quot;;
  import { HttpLink } from &quot;apollo-link-http&quot;;
  import fetch from &quot;isomorphic-unfetch&quot;;
  import createApolloClient from './create';
  
  let apolloClient = null;
  
  /**
   * Creates and provides the apolloContext
   * to a next.js PageTree. Use it by wrapping
   * your PageComponent via HOC pattern.
   * @param {Function|Class} PageComponent
   * @param {Object} [config]
   * @param {Boolean} [config.ssr=true]
   */
  export function withApollo(PageComponent, { ssr = true } = {}) {
    const WithApollo = ({ apolloClient, apolloState, ...pageProps }) =&gt; {
      const client = apolloClient || initApolloClient(apolloState);
  
      return (
        &lt;ApolloProvider client={client}&gt;
          &lt;PageComponent {...pageProps} /&gt;
        &lt;/ApolloProvider&gt;
      );
    };
  
    // Set the correct displayName in development
    if (process.env.NODE_ENV !== &quot;production&quot;) {
      const displayName =
        PageComponent.displayName || PageComponent.name || &quot;Component&quot;;
  
      if (displayName === &quot;App&quot;) {
        console.warn(&quot;This withApollo HOC only works with PageComponents.&quot;);
      }
  
      WithApollo.displayName = `withApollo(${displayName})`;
    }
  
    if (ssr || PageComponent.getInitialProps) {
      WithApollo.getInitialProps = async (ctx) =&gt; {
        const { AppTree } = ctx;
  
        // Initialize ApolloClient, add it to the ctx object so
        // we can use it in `PageComponent.getInitialProp`.
        const apolloClient = (ctx.apolloClient = initApolloClient(
          {},
          ctx.req.headers.cookie
        ));
  
        // Run wrapped getInitialProps methods
        let pageProps = {};
        if (PageComponent.getInitialProps) {
          pageProps = await PageComponent.getInitialProps(ctx);
        }
  
        // Only on the server:
        if (typeof window === &quot;undefined&quot;) {
          // When redirecting, the response is finished.
          // No point in continuing to render
          if (ctx.res &amp;&amp; ctx.res.finished) {
            return pageProps;
          }
  
          // Only if ssr is enabled
          if (ssr) {
            try {
              // Run all GraphQL queries
              const { getDataFromTree } = await import(&quot;@apollo/react-ssr&quot;);
              await getDataFromTree(
                &lt;AppTree
                  pageProps={{
                    ...pageProps,
                    apolloClient,
                  }}
                /&gt;
              );
            } catch (error) {
              // Prevent Apollo Client GraphQL errors from crashing SSR.
              // Handle them in components via the data.error prop:
              // https://www.apollographql.com/docs/react/api/react-apollo.html#graphql-query-data-error
              console.error(&quot;Error while running `getDataFromTree`&quot;, error);
            }
  
            // getDataFromTree does not call componentWillUnmount
            // head side effect therefore need to be cleared manually
            Head.rewind();
          }
        }
  
        // Extract query data from the Apollo store
        // @ts-ignore
        const apolloState = apolloClient.cache.extract();
  
        return {
          ...pageProps,
          apolloState,
        };
      };
    }
  
    return WithApollo;
  }
  
  /**
   * Always creates a new apollo client on the server
   * Creates or reuses apollo client in the browser.
   * @param  {Object} initialState
   */
  function initApolloClient(initialState = {}, cookie = &quot;&quot;) {
    // Make sure to create a new client for every server-side request so that data
    // isn&quot;t shared between connections (which would be bad)
  
    if (typeof window === &quot;undefined&quot;) {
      return createApolloClient(initialState, cookie);
    }
  
    // Reuse client on the client-side
    if (!apolloClient) {
      // @ts-ignore
      apolloClient = createApolloClient(initialState);
    }
  
    return apolloClient;
  }
  
  </code></pre>
  <p><a href="https://i.stack.imgur.com/1MA97.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1MA97.png" alt="Result of the query with @guard directive" /></a></p>