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

Session not reflected upon first login #171

Open
Rykuno opened this issue Jan 16, 2021 · 7 comments
Open

Session not reflected upon first login #171

Rykuno opened this issue Jan 16, 2021 · 7 comments
Labels
bug Something isn't working

Comments

@Rykuno
Copy link
Contributor

Rykuno commented Jan 16, 2021

I noticed when initializing the app, the session within _app.js and subsequently apollo are not reflected with the users's creds.

It appears as the session goes through the callbacks of next-auth but is never reflected in the UI until a subsequent refresh.

I noticed by being unable to click the logout button within the nav right after signing in. I haven't dove into the issue as its late here but I'll see what I can find tomorrow and update with reproducible code need be.

@ghoshnirmalya ghoshnirmalya added the bug Something isn't working label Jan 16, 2021
@ghoshnirmalya
Copy link
Owner

@Rykuno Thank you for posting this issue.

In development mode, the Next.js application (specifically NextAuth) was unable to connect to the Postgres database. I've pushed one commit which should fix that issue.

Can you please pull the latest master branch and check if the issue still persists?

@Rykuno
Copy link
Contributor Author

Rykuno commented Jan 16, 2021

Okay so I think I might have found a solution but not per say the issue. I do believe it is with the next-auth library.

There's two issues.

  1. The session within _app.tsx is not updated and subsequently passed to apolloClient upon login. Refreshing the page will fix the issue.
  2. Some providers append a "#" to the url for some weird reason. This issue is related signIn callbackUrl contains a # at the end? nextauthjs/next-auth#532

I was able to solve both of these through configuring my _app.tsx as such but we lose auto static optimization from next due to the use of getInitialProps.

const MyApp = ({ Component, pageProps, router, session }: AppProps) => {
  const apolloClient = useApollo(pageProps.initialApolloState, session?.token);
  
  useEffect(() => {
    if (router.asPath.endsWith("#")) router.push(router.pathname);
  });

  return (
    <>
      <Head>
        <link rel="shortcut icon" href="/images/favicon.ico" />
      </Head>
      <NextAuthProvider session={session}>
        <ApolloProvider client={apolloClient}>
          <Layout>
            <Component {...pageProps} />
          </Layout>
        </ApolloProvider>
      </NextAuthProvider>
    </>
  );
};

MyApp.getInitialProps = async context => {
  const appProps = await App.getInitialProps(context);
  const session = await getSession(context);

  return {
    ...appProps,
    session
  };
};

export default MyApp;

Oh and on a side note docker-compose.yml needs a mounted volume for the copy in Dockerfile to persist I think.

    volumes:
      - ./migrations:/hasura-migrations
      - ./metadata:/hasura-metadata

@ghoshnirmalya
Copy link
Owner

@Rykuno Thank you for the detailed response.

We'll most probably have to wait for both of these issues to be fixed in NextAuth rather than adding getInitialProps which will prevent auto static optimization. But, this issue would be a good resource in case someone else is coming across a similar issue.

Oh and on a side note docker-compose.yml needs a mounted volume for the copy in Dockerfile to persist I think.

Would you be interested in creating a PR for that?

@Rykuno
Copy link
Contributor Author

Rykuno commented Jan 17, 2021

@Rykuno Thank you for the detailed response.

We'll most probably have to wait for both of these issues to be fixed in NextAuth rather than adding getInitialProps which will prevent auto static optimization. But, this issue would be a good resource in case someone else is coming across a similar issue.

Oh and on a side note docker-compose.yml needs a mounted volume for the copy in Dockerfile to persist I think.

Would you be interested in creating a PR for that?

Created a PR for the volume issue. To reference the first issue I raised a question in the Next-Auth repo in which a response clarified the issue.
nextauthjs/next-auth#1130 (comment)

I fixed this through moving the ApolloProvider initialization to a middleware layout of sorts to opt back into static optimization. There is probably a cleaner solution though. This issue occurs when you're redirected from signin directly to a page where data fetching utilizing apollo is required.

The token would be undefined at this location in apolloClient.tsx without a work around and would fail if authentication is required. To view it in the example, set the signin with a callback to the feeds page for example signin({callbackUrl: "http://localhost:3000/feeds"

const createHttpLink = (token: string) => {
  const httpLink = new HttpLink({
    uri: process.env.NEXT_PUBLIC_API_URL || "http://localhost:8080/v1/graphql",
    credentials: "include",
    headers: token
      ? { Authorization: `Bearer ${token}` }
      : { "X-Hasura-Role": `anonymous` },
    fetch
  });
  return httpLink;
};

@tconroy
Copy link

tconroy commented Apr 10, 2021

Hello! 👋 I believe I am running into a similar issue with this boilerplate, but I'm not entirely sure what the solution was. @Rykuno, would you mind elaborating further on what changes you made? Particularly the middleware layout? Is that just moving the provider into the <Layout> component?

The issue I am seeing is that on first visit to the /feeds route after authentication, the token is undefined. If I refresh the page, the token is set and the route behaves as expected.

I'm seeing this error in the console, too, which goes away after a refresh:

"cannot start as connection_init failed with : Could not verify JWT: JWSError (CompactDecodeError Invalid number of parts: Expected 3 parts; got 1)"

@Rykuno
Copy link
Contributor Author

Rykuno commented Apr 11, 2021

Hello! 👋 I believe I am running into a similar issue with this boilerplate, but I'm not entirely sure what the solution was. @Rykuno, would you mind elaborating further on what changes you made? Particularly the middleware layout? Is that just moving the provider into the <Layout> component?

The issue I am seeing is that on first visit to the /feeds route after authentication, the token is undefined. If I refresh the page, the token is set and the route behaves as expected.

I'm seeing this error in the console, too, which goes away after a refresh:

"cannot start as connection_init failed with : Could not verify JWT: JWSError (CompactDecodeError Invalid number of parts: Expected 3 parts; got 1)"

Wish i could chime in here but I don't remember how I exactly solved the original issue. We migrated to firebase auth very soon after I fixed this.

Their documentation was poor at communicating how it all worked. I created a ticket at the next-auth repoand got an explantation here

@tconroy
Copy link

tconroy commented Apr 11, 2021

No worries, thanks for the response! I think I have a workaround by wrapping each page with a <ApolloClientProvider> which pulls session off the static props and configures the client that way. Not ideal, and I think it technically loses static rendering, but at least it unblocks me for now.

If anyone can find a more elegant solution that preserves static generation, let me know :-)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

3 participants