This quickstart showcases how to correctly add authentication to a Next.js 14 project using the new App Router and Server Components. The other parts of the SDK (Storage / GraphQL/ Functions) should work the same as before.
-
Saving the auth session
To enable authentication with Server Components we have to store the auth session in a cookie. This should be done right after any signIn or signUp operation. See example here.
-
Oauth & refresh session middleware
Create a middleware at the root of your project that calls the helper method
manageAuthSession. Feel free to copy paste the the contents of the/utilsfolder to your project. The second argument formanageAuthSessionis for handling the case where there's an error refreshing the current session with therefreshTokenstored in the cookie.import { manageAuthSession } from '~/utils/nhost'; import { NextRequest, NextResponse } from 'next/server'; export async function middleware(request: NextRequest) { return manageAuthSession(request, () => NextResponse.redirect(new URL('/auth/sign-in', request.url)), ); }
-
Protected routes
To make sure only authenticated users access some Server Components, wrap them in the Higher Order Server Component
withAuthAsync.import withAuthAsync from '~/utils/auth-guard' const MyProtectedServerComponent = async () => { return <h2>Protected</h2> } export default withAuthAsync(MyProtectedServerComponent)
-
Clone the repository
git clone https://github.com/jovermier/mc-starter cd nhost -
Install and build dependencies
pnpm install pnpm build
-
Terminal 1: Start the Nhost Backend
Make sure you have the Nhost CLI installed.
nhost up
-
Terminal 2: Start the Next.js application
pnpm dev