Next.js Discord

Discord Forum

protected routes

Answered
American Chinchilla posted this in #help-forum
Open in Discord
Avatar
American ChinchillaOP
How to create a protected route that only user who is authenticated can visit without copy pasting code for each page to check whether user is authed

For example how to make all pages under /dashboard route protected?
Im using nextjs 13 app dir
Answered by The ORM Joker
import { type NextRequest, NextResponse } from 'next/server';

const PUBLIC_ROUTES = ['/sign-in', '/sign-up'];

// This function can be marked `async` if using `await` inside
export function middleware(request: NextRequest) {
  if (
    request.nextUrl.pathname.startsWith('/profile') &&
    request.nextUrl.pathname.replace(/\/profile\/(.*)/gm, '') === ''
  )
    return;
  if (PUBLIC_ROUTES.includes(request.nextUrl.pathname)) {
    if (request.cookies.get('token')?.value) {
      return NextResponse.redirect(new URL('/', request.url));
    }
    return;
  } else if (!request.cookies.get('token')?.value)
    return NextResponse.redirect(new URL('/sign-up', request.url));
}

export const config = {
  matcher: ['/((?!.*\\..*|_next).*)', '/(api|trpc)(.*)'],
};


I am currently using this middleware and it works as expected
View full answer

7 Replies

Avatar
The ORM Joker
use middleware
Avatar
American ChinchillaOP
Could you provide me an example how to set up this
Avatar
The ORM Joker
import { type NextRequest, NextResponse } from 'next/server';

const PUBLIC_ROUTES = ['/sign-in', '/sign-up'];

// This function can be marked `async` if using `await` inside
export function middleware(request: NextRequest) {
  if (
    request.nextUrl.pathname.startsWith('/profile') &&
    request.nextUrl.pathname.replace(/\/profile\/(.*)/gm, '') === ''
  )
    return;
  if (PUBLIC_ROUTES.includes(request.nextUrl.pathname)) {
    if (request.cookies.get('token')?.value) {
      return NextResponse.redirect(new URL('/', request.url));
    }
    return;
  } else if (!request.cookies.get('token')?.value)
    return NextResponse.redirect(new URL('/sign-up', request.url));
}

export const config = {
  matcher: ['/((?!.*\\..*|_next).*)', '/(api|trpc)(.*)'],
};


I am currently using this middleware and it works as expected
Answer
Avatar
American ChinchillaOP
Okay thanks ill look into it soon
Only thing how does it gets registered do i just make middleware.ts file in app dir and export middleware function
Avatar
The ORM Joker
create a middleware.ts file in the root of your project
Avatar
American ChinchillaOP
ah okay and it just works