Convention

All pages inside

/apps/web/app/app, folder are private by default.
All pages inside

/apps/web/app/home folder are public by default.

So, if you want to add a new private page to your application, make sure to add it inside

/apps/web/app/app folder.

How TurboStack ensures authentication?

We created a NextJS Middleware to ensure that all pages inside app folder need an authentified user to be available.

Here is the code for our AppMiddleware:

apps/web/lib/middleware/app.ts
export async function AppMiddleware(req: NextRequest) {
  
  // get the current session from request cookies
  const session = (await getToken({ 
    req,
    secret: process.env.NEXTAUTH_SECRET,
  })) as {
    email?: string;
    user?: {
      id: string;
    };
  };
  
  // if the session is undefined and the requested url is not public, then redirect to sign-in.
  if (!session?.email && !isPublic(req)) {
    return NextResponse.redirect(
      new URL(
        '/sign-in',
        req.url
      )
    )
  }

  const searchParams = req.nextUrl.searchParams.toString();
  const searchParamsString = searchParams.length > 0 ? `?${searchParams}` : "";
  const fullPath = `${req.nextUrl.pathname}${searchParamsString}`;

  return NextResponse.rewrite(new URL(`/app${fullPath}`, req.url))
}

function isPublic(req: NextRequest) { // <- if you need more public pages, change this function.
  return ['/sign-in'].includes(req.nextUrl.pathname)
}