Why does getServerSideProps in next+apollo throws an Unauthorized error?

Viewed 71

I have implemented authorization using cookies, when ApolloClient is initialized, an authorization link is specified, where there is a token in the headers. But when trying to load data with getServerSideProps I always get an Unauthorized error even though without getServerSideProps everything works. This is my first experience with apollo, so I don't quite understand how to fix it.

My ApolloClient:

import { parseCookies } from 'nookies'
import { setContext } from '@apollo/client/link/context';
import { ApolloClient, InMemoryCache, createHttpLink } from '@apollo/client'

const cookies = parseCookies()

const httpLink = createHttpLink({
    uri: 'http://localhost:3001/graphql',
});

const authLink = setContext((_, { headers }) => {
    const token = cookies.access_token
    return {
        headers: {
            ...headers,
            authorization: token ? `Bearer ${token}` : "",
        }
    }
});

export let client = new ApolloClient({
    cache: new InMemoryCache(),
    credentials: 'same-origin',
    link: authLink.concat(httpLink),
})

Component with getServerSideProps:

export default function Suggestions({ users }: any) {

    return (<MainLayout>
        {JSON.stringify(users)}
    </MainLayout>)
}

export async function getServerSideProps(context: GetServerSidePropsContext) {
    const { data } = await client.query({
        query: GET_USERS
    });

    return {
        props: { users: data.users },
    }
}

Main.js file on the backend (backend on Nestjs)

async function bootstrap() {
  const app = await NestFactory.create<NestExpressApplication>(AppModule, { cors: true });
  app.useGlobalPipes(new ValidationPipe())
  app.useGlobalGuards(new JwtAuthGuard(new Reflector()))
  app.enableCors({
    origin: 'http://localhost:3000',
    credentials: true,
    allowedHeaders: 'Origin,X-Requested-With,Content-Type,Accept,Authorization,authorization'
  })

  await app.listen(3001);
}

bootstrap();

And Graphql in App.module on backend

@Module({
  imports: [
    GraphQLModule.forRoot({
      autoSchemaFile: path.join(process.cwd(), 'src/schema/gql'),
      sortSchema: true,
      driver: ApolloDriver,
      context: ({ req, res }) => ({ req, res }),
      cors: {
        origin: 'http://localhost:3000',
        credentials: true,
      }
    }),

0 Answers
Related