I got it working doing the following, hit me up if you have any questions
Docs for reference
Middleward Route - withMiddlewareAuthRequired | @auth0/nextjs-auth0
Session/Route auth - GetSession | @auth0/nextjs-auth0
Setting up the api auth0 route - REQUIRED
Create a new route under src/app/api/auth/[auth0]/route.ts
Contents would be
// app/api/auth/[auth0]/route.js
import { handleAuth } from '@auth0/nextjs-auth0';
export const GET = handleAuth();
Env variables required
Make sure to set this env variables in your app as they are required by the auth0 lib during run time
AUTH0_SECRET
AUTH0_BASE_URL
AUTH0_ISSUER_BASE_URL
AUTH0_CLIENT_ID
AUTH0_CLIENT_SECRET
How to protect your routes
Option 1: Middleware
Create a new file middleware.ts or middleware.js at the same level as app inside your src folder with the following contents
// src/app/middleware.ts
import { withMiddlewareAuthRequired } from '@auth0/nextjs-auth0/edge';
export default withMiddlewareAuthRequired();
This will make sure that all your routes are protected. You can create a config on it to protect certain routes if you’d like
// src/app/middleware.ts
import { withMiddlewareAuthRequired } from '@auth0/nextjs-auth0/edge';
export default withMiddlewareAuthRequired();
export const config = {
matcher: '/about/:path*',
};
Option 2: Route Level
You just need to export a GET function as a constant wrapping your route under teh with api auth required function that the lib provides
// app/api/<route directory name>/route.ts
import { withApiAuthRequired } from '@auth0/nextjs-auth0';
import { NextResponse } from 'next/server';
export const GET = withApiAuthRequired(async function GET(req) {
const res = new NextResponse();
return new NextResponse('Seems to be working', {
status: 200
})
});
Accessing the user session
Go to your route and import the get session function from lib
import { getSession } from '@auth0/nextjs-auth0';
Then just call the get session with the request and a new response object, that’s pretty much it
// app/api/<route directory name>/route.ts
import { getSession } from '@auth0/nextjs-auth0';
import { NextResponse } from 'next/server';
export async function GET(req) {
const res = new NextResponse();
const session = await getSession(req, res);
return new NextResponse(`Logged in as ${session?.user.nickname}`, {
status: 200
})
});