Next.js Fundamentals Authentication
- Authentication is an important piece of many sites. I currently choose to use the package 'next-auth'. There is currently v5 which has some breaking changes to v4; this tutorial of setting up authenticaion in Next.js 14 is utlizing v5.next-auth. In this page let us highlight some important pieces of authorization within Next.js.
Summaryof setting up next-auth in Next.js includes the following:
1. Install next-auth
2. Define .env var
2.5 Create OAuth Id's & Secrete's
3. Create auth.ts file
4. Add SessionProvider & wrap layout
5. Add API ...nextauth route
Details of setting up next-auth in Next.js includes the following:
1. Install next-auth
To install next-auth we add the package.1yarn add next-auth
2. Define .env var
In our .env file we add the follow:
In v5 the naming convention is nicer since it's all prefixed with "Auth":- * prefix with AUTH_
- * then Provider name
- * Suffix is ID || Client
1AUTH_SECRET="" 2AUTH_GOOGLE_ID="" 3AUTH_GOOGLE_SECRET=""
2.5 Create OAuth Id's & Secret's
The OAuth provider Id & Secrete is obtained from each provider & is slightly different for each.
For example this is a good resource for Setting up Google Oauth 2.0 documentation
There are is a whole large list of Auth.js OAuth providers1openssl rand -base64 32
3. auth.ts
Creating auth.ts in root directory allows us to add config & authentication for our providers.1import NextAuth from "next-auth” 2import GithubProvider from "next-auth/providers/github” 3 4export const authOptions = { 5 // Configure auth providers here 6 providers: [ GithubProvider({ 7 clientId: process.env.GITHUB_ID, 8 clientSecret: process.env.GITHUB_SECRET, 9 }), 10 // ...add more providers here such as fb or apple 11 ], 12}
4. Add SessionProvider & wrap layout
Session provider we can add the import & the wrap our layout.1import { SessionProvider } from "next-auth/react"; 2 3return ( 4 <SessionProvider> 5 <html> 6 <body ...Inside-of-Layout 7 </html> 8 </SessionProvider> 9
5. Add API ...nextauth route
We need to add the API route & the relative path is `app/api/auth/[...nextauth]/route.ts`
In next-auth v5 this file is much simplified and the config is in our auth.ts file;1export { GET, POST } from 'auth';
Then next we can create login & out sections. Also protect our pages. This section covers the basics of next-auth v5.
Then next we move on to roles Official Auth JS Role based access
We can also implement middleware to cover the whole app & here is some documentation: Middleware official page on Next.js