在使用Apollo Client和Next.js进行身份验证时,可以通过以下步骤解决问题:
npm install apollo-boost graphql next-with-apollo react-apollo
apollo.js
文件:import { ApolloClient, InMemoryCache, HttpLink } from 'apollo-boost';
import fetch from 'isomorphic-unfetch';
export default function createApolloClient(initialState, ctx) {
const link = new HttpLink({
uri: 'YOUR_GRAPHQL_API_ENDPOINT',
credentials: 'include', // Send cookies along with requests
fetch: !process.browser && fetch, // Use isomorphic-unfetch if server-side
});
return new ApolloClient({
connectToDevTools: process.browser,
ssrMode: !process.browser, // Disable server-side rendering (SSR) when running on client
link,
cache: new InMemoryCache().restore(initialState),
});
}
请确保将YOUR_GRAPHQL_API_ENDPOINT
替换为您的GraphQL API的实际端点。
import withApollo from 'next-with-apollo';
import ApolloClient from 'apollo-boost';
import { ApolloProvider } from 'react-apollo';
import createApolloClient from './apollo';
export default withApollo(
({ initialState, ctx }) => createApolloClient(initialState, ctx),
{
render: ({ Page, props }) => (
),
}
);
withApollo
包装组件,并在getInitialProps
中获取和设置身份验证相关的信息:import { gql } from 'apollo-boost';
import { withApollo } from '../lib/apollo';
const ProfilePage = ({ user }) => (
Profile Page
{user && Welcome, {user.name}!
}
);
ProfilePage.getInitialProps = async ({ apolloClient, ctx }) => {
const { data } = await apolloClient.query({
query: gql`
query {
currentUser {
name
}
}
`,
context: {
headers: {
authorization: ctx.req ? ctx.req.headers.cookie || '' : '', // Pass cookies along with the request
},
},
});
return {
user: data.currentUser,
};
};
export default withApollo(ProfilePage);
在此示例中,我们使用currentUser
查询来获取当前用户的名称。我们将authorization
标头设置为传递的cookie,以便服务器可以进行身份验证。
请确保将YOUR_GRAPHQL_API_ENDPOINT
替换为您的GraphQL API的实际端点。
这样,您的Apollo Client和Next.js身份验证问题应该得到解决。您可以根据自己的需求进行修改和扩展。