Nhost NextJS library
npm install @maherbold/nextjsbash
With npm
npm install @nhost/nextjs graphql
With Yarn
yarn add @nhost/nextjs graphql
`
Initializing
Initialize a single nhost instance and wrap your app with the NhostProvider.
`jsx title=pages/_app.js
import type { AppProps } from 'next/app'
import { NhostClient, NhostProvider } from '@nhost/nextjs'
const nhost = new NhostClient({
subdomain: '',
region: ''
})
function MyApp({ Component, pageProps }: AppProps) {
return (
)
}
export default MyApp
`
Server-Side Rendering (SSR)
You need to load the session from the server first from getServerSideProps. Once it is done, the _app component will make sure to load or update the session through pageProps.
`jsx title=pages/ssr-page.tsx
import { NextPageContext } from 'next'
import React from 'react'
import {
getNhostSession,
NhostSession,
useAccessToken,
useAuthenticated,
useUserData
} from '@nhost/nextjs'
export async function getServerSideProps(context: NextPageContext) {
const nhostSession = await getNhostSession(
{ subdomain: '', region: '' },
context
)
return {
props: {
nhostSession
}
}
}
const ServerSidePage: React.FC<{ initial: NhostSession }> = () => {
const isAuthenticated = useAuthenticated()
const user = useUserData()
const accessToken = useAccessToken()
if (!isAuthenticated) {
return User it not authenticated
}
return (
{user?.displayName} is authenticated
Access token: {accessToken}
)
}
export default ServerSidePage
`
Apollo GraphQL
You can use Apollo's GraphQL Client together with Next.js and Nhost.
$3
`bash
With npm
npm install @nhost/react-apollo @apollo/client
With Yarn
yarn add @nhost/react-apollo @apollo/client
`
$3
Wrap the Next.js app with the NhostApolloProvider and make sure the NhostApolloProvider is nested inside the NhostProvider.
`jsx title=pages/_app.js
import type { AppProps } from 'next/app'
import { NhostClient, NhostProvider } from '@nhost/nextjs'
import { NhostApolloProvider } from '@nhost/react-apollo'
const nhost = new NhostClient({
subdomain: '',
region: ''
})
function MyApp({ Component, pageProps }: AppProps) {
return (
)
}
export default MyApp
``