Skip to content

Commit

Permalink
fix(apollo): fixes missing bearer token on api calls
Browse files Browse the repository at this point in the history
Updates to set the correct auth token for api calls
  • Loading branch information
anguspiv committed Feb 23, 2023
1 parent b3bebb5 commit 376117b
Show file tree
Hide file tree
Showing 6 changed files with 51 additions and 6 deletions.
1 change: 1 addition & 0 deletions .storybook/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ module.exports = {
'@emotion/core': '@emotion/react',
'emotion-theming': '@emotion/react',
'@components': path.resolve(__dirname, '../src/components'),
'@context': path.resolve(__dirname, '../src/context'),
'@pages': path.resolve(__dirname, '../pages'),
'@db': path.resolve(__dirname, '../src/db'),
'@graphql': path.resolve(__dirname, '../src/graphql'),
Expand Down
1 change: 1 addition & 0 deletions jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ module.exports = {
https://jestjs.io/docs/webpack#handling-static-assets */
'^.+\\.(jpg|jpeg|png|gif|webp|avif|svg)$': '<rootDir>/__mocks__/fileMock.js',
'^@components(.*)$': '<rootDir>/src/components$1',
'^@context(.*)$': '<rootDir>/src/context$1',
'^@db(.*)$': '<rootDir>/src/db$1',
'^@graphql(.*)$': '<rootDir>/src/graphql$1',
'^@utils(.*)$': '<rootDir>/src/utils$1',
Expand Down
4 changes: 2 additions & 2 deletions pages/_app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ import { ChakraProvider } from '@chakra-ui/react';
import { SessionProvider } from 'next-auth/react';
import { ApolloProvider } from '@apollo/client';
import type { AppProps } from 'next/app';
import PageLayout from '../src/components/layout/PageLayout';
import client from '../src/utils/apollo-client';
import PageLayout from '@components/layout/PageLayout';
import client from '@utils/apollo-client';
import '../styles/globals.css';

// eslint-disable-next-line react/function-component-definition
Expand Down
25 changes: 24 additions & 1 deletion pages/api/auth/[...nextauth].ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import NextAuth from 'next-auth';
import NextAuth, { Session } from 'next-auth';
import { PrismaAdapter } from '@next-auth/prisma-adapter';
import EmailProvider from 'next-auth/providers/email';
import GoogleProvider from 'next-auth/providers/google';
Expand Down Expand Up @@ -59,6 +59,10 @@ const createUser = async ({ user }: NextAuthMessage) => {
}
};

export interface AuthSession extends Session {
accessToken?: unknown;
}

export default withSentry(
NextAuth({
adapter,
Expand All @@ -68,5 +72,24 @@ export default withSentry(
events: {
createUser,
},
callbacks: {
async jwt({ token, account }) {
// Persist the OAuth access_token to the token right after signin
if (account) {
// eslint-disable-next-line no-param-reassign
token.accessToken = account.access_token;
}
return token;
},
async session({ session, token }) {
// Send properties to the client, like an access_token from a provider.

const newSession: AuthSession = {
...session,
accessToken: token.accessToken,
};
return newSession as Session;
},
},
}),
);
25 changes: 22 additions & 3 deletions src/utils/apollo-client.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,36 @@
import { ApolloClient, InMemoryCache } from '@apollo/client';
import { ApolloClient, InMemoryCache, from } from '@apollo/client';
import { createUploadLink } from 'apollo-upload-client';
import { getSession } from 'next-auth/react';
import { getBaseUrl } from '@utils/getBaseUrl';
import logger from '@utils/logger';
import { ContextSetter, setContext } from '@apollo/client/link/context';
import { AuthSession } from '../../pages/api/auth/[...nextauth]';

const BASE_URL = getBaseUrl();
const uri = `${BASE_URL}/api/graphql`;

logger.info(`Base URL: ${BASE_URL}\n GraphQL uri: ${uri}`);

const httpLink = createUploadLink({ uri, credentials: 'include' });

const contextSetter: ContextSetter = async (operation, { headers }) => {
const session = (await getSession()) as AuthSession;

const modifiedHeader = {
headers: {
...headers,
authorization: session?.accessToken ? `Bearer ${session.accessToken}` : '',
},
};

return modifiedHeader;
};

const authLink = setContext(contextSetter);

const client = new ApolloClient({
uri,
cache: new InMemoryCache(),
link: createUploadLink({ uri }),
link: from([authLink, httpLink]),
});

export default client;
1 change: 1 addition & 0 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
"baseUrl": "./",
"paths": {
"@components/*": ["src/components/*"],
"@context/*": ["src/context/*"],
"@db/*": ["src/db/*"],
"@graphql/*": ["src/graphql/*"],
"@utils/*": ["src/utils/*"],
Expand Down

1 comment on commit 376117b

@vercel
Copy link

@vercel vercel bot commented on 376117b Feb 23, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.