Next.js Discord

Discord Forum

API'S GOT NOT GETTING CALLED IN LAYOUT.TSX FILE

Unanswered
DhrishP1 posted this in #help-forum
Open in Discord
This is my code but I the api is not getting called , it is constantly giving me status "200" even though it is never going to the api route. I have added cache "no-store" to not cache the api route.
I am also getting the UseContext error once when I change the layout file and it fixes itself.

I have provided the folder structure of the api folders and question page layout.tsx along with the API.

Also I have changed the request from GET TO POST TO DEBUG

I think it can be :
1. If conditions is not allowed in layout.tsx(useContext error)
2. it is getting cached but I use
export const revalidate = 0;
but still the same thing is occuring so not possible
3. the status is getting cached somehow ( idk how this might be occuring but I am constantly getting 200 status even though I am not caching anything) - maybe a nextjs 14 bug?

373 Replies

@Ray
import { useSession } from "next-auth/react";

export const useCurrentUser = () => {
  const session = useSession();

  return session.data?.user;
};
you can't use react context in route handler
@Ray you can't use react context in route handler
you mean api route?
what do you mean route handler
@Ray route.ts
yes how should I get the userId?
@DhrishP1 yes how should I get the userId?
use getServerSession
import { getServerSession } from "next-auth/next"
import { authOptions } from "pages/api/auth/[...nextauth]"

export default async function Page() {
  const session = await getServerSession(authOptions)
  return <pre>{JSON.stringify(session, null, 2)}</pre>
}
@Ray use `getServerSession`
in route.ts right?
@Ray you should do it in page.ts
no in api , how should I get the userId?
you wanna render the data on page.ts right?
yes
you don't need the route.ts for fetching data for the page.ts
just do it on the page.ts
yes , I will read after this chat but what do you mean by and you shouldn't fetch route handler in server component
move the prisma operation to your page.ts
@Ray move the prisma operation to your page.ts
in the layout right?
layout will also work
or only page.tsx
you could do it in layout.ts or page.ts depend on how you render the page
?
they are server component by default which can do server stuff
@Ray you could do it in layout.ts or page.ts depend on how you render the page
yea but can you explain why route handler dont work in layout.ts
so server comp cant call server comp?
just like getServerSideProps in pages router
@DhrishP1 so server comp cant call server comp?
what do you mean?
you can render server component like react component
<ServerComponent />
@Ray you can render server component like react component
I meant you can't call another other functions
in a server side component
like calling route handler from layout.ts
?
you can but you shouldn't
read the article lol
Ok you can right? then why my layout.ts not working
because you are trying to use react context in the api route
@Ray read the article lol
I am so confused lol , sorry for the confusion I am causing you too
and you should be returning a Response instead of throwing an error in the api route
@Ray because you are trying to use react context in the api route
ok should I use getServerSession in route handler for userId?
yes
@Ray yes
okay I will reas the article now lol
I need to stop watching yt vids now lol
time to read some docs
this is the first time making a project on my own
so I am making very fundamental mistakes , thanks
for helping
@Ray https://www.youtube.com/watch?v=RBM03RihZVs video version for the article
thanks a lot❤️❤️ , please be online for few minutes I am changing the route handlers
@Ray I am using next-auth v5*
yea
then use auth() instead
@Ray then use `auth()` instead
can you show the syntax
is it like this
@DhrishP1 Click to see attachment
what is the file path for this file
@Ray what is the file path for this file
yup got the auth
it was @/auth
import { auth } from 'that file'
on the api route
then const session = await auth()
yes rest everything else is fine right?
should rest of the code work now? I will migrate from api routes to
layout
after this
@DhrishP1 yes rest everything else is fine right?
  const session = await auth();
  if (!session) {
    return new NextResponse("", { status: 401 });
  }
dont throw an error
lmao copilot did it
I will change it
thanks alot man
you helped me a bunch
❤️❤️❤️
@DhrishP1 thanks alot man
np
does it work now?
@Ray does it work now?
testing
@Ray not working😭😭
any error
@Ray any error
same error
useContext
@DhrishP1 same error
could you show the code for the api route
@Ray could you show the code for the api route
migrated the code to layout.ts
but why is it not working
@DhrishP1 migrated the code to layout.ts
show the code
@Ray show the code
It is working now in layout.ts , lemme send one more code similar which is not working
import { auth } from "@/auth";
import { UserRole } from "@prisma/client";
import { NextResponse } from "next/server";

export async function GET() {
  const role = await auth();

  if (role?.user.role === UserRole.ADMIN) {
    return new NextResponse(null, { status: 200 });
  }

  return new NextResponse(null, { status: 403 });
}
the api is not getting called
import React from "react";

const AdminLayout = async ({ children }: { children: React.ReactNode }) => {
  const isAdmin = await fetch(`${process.env.NEXT_PUBLIC_APP_URL}/api/admin`, {
    next: { revalidate: 86400 },
  });
  console.log(isAdmin.status);
  if (isAdmin.status !== 200) {
    return <div>403 Forbidden</div>;
  }

  return <div>{children}</div>;
};

export default AdminLayout;
layout.tsx
debugging
not the issue here
I was constant 200 status
without calling the api
so for debugging , changed the cache values from 0 to 864000
@Ray It was working well before without auth()
Idk what happened
why is it giving only 200 status
what are you expecting?
are you logged in as admin?
@Ray what are you expecting?
the role of user is user
should lemme enter
gimme 403 forbidden
it is not calling the api route
it is cached or someting
thing*
I use export const revalidate
why don't you just call auth() in the layout.ts instead?
all the methods
@Ray why don't you just call auth() in the layout.ts instead?
I can , it would work but why is this thing not working?
it should work
it was working well
because you set it revalidate in 86400
@Ray because you set it revalidate in 86400
no , just removed it as you said
still no luck
clear the cache
rm -rf .next/cache/fetch-cache
btw, GET endpoint is static by default
in production
@Ray in production
I didnt get you
static?
but it should call the api endpoint atleast
@Ray rm -rf .next/cache/fetch-cache
I am trying this
@Ray cached
yup , tried revalidate from both fetch and
export const revalidate = 0;
now using rm rf method
hope it fixes it
nope
still cached somewhere
deleted .next
still
removed caching from browser also
do it in the page.ts
idk what other method is left to revalidate cache
@Ray do it in the page.ts
I can , that's not the issue but why isn't it working
any idea?
did it hit the endpoint now
console.log(role?.user.role === UserRole.ADMIN)
@Ray did it hit the endpoint now
no
thats the main issue
it's not hitting the endpoint
could you show the folder structure
and what url are you accessing
api/admin
you are accessing /api/admin?
yea
to check whether the role is USER or ADMIN
can you show a screenshot
@Ray can you show a screenshot
of?
I have send both of the files above
page.tsx and route.ts
what url are you accessing
i don't get it
pushed to production , still not working
not a dev server error
@Ray i don't get it
same I am also so done with this bug
Idk where tf is it caching the
result
should I try deleting the node_modules?
could you share the repo
it is not the latest push
but still
it is the same code
@Ray Click to see attachment
what is the issue?
it is working for you
not for me
have you tried to restart the dev server
yup
I am debugging this for 2-3hrs
push your code
pushed rn
will take 5 mins to get into prod
@DhrishP1 pushed rn
  const isAdmin = await fetch(`${process.env.NEXT_PUBLIC_APP_URL}/api/admin`, {
    cache: "no-store",
  });
it is
how?
it is not caching
anything
it is for not caching
it is cached if you don't set it
so should I set it
or remove it
you should just call auth() here
yea I am gonna do that
but what is the issue
it just makes code more messy
doing all these in layout
fetch by default will cache the request
@DhrishP1 doing all these in layout
you should do this in middleware instead of layout
they can bypass the your authentication check
@Ray you should do this in middleware instead of layout
no these is only for admin routes
so cant add it in middleware
changed to {cache:'no-store'}
still the same thing
im not logged in
you should console.log(role?.user.role === UserRole.ADMIN) in the api route
it is not reaching the api endpoint only
I have console.log ('hi')
on the first line
it is not hitting the endpoint only
and also if fetch caches by default , it should not work in prod
on refresh or on navigation?
still it is
@Ray on refresh or on navigation?
both
no wait
refresh
I have not used any links to navigate
it is a admin route
update to latest version of next
I don't have this issue
@Ray update to latest version of next
that is?
14.?
14.1.4
it is npm i next@14.1.4?
right
next@latest
not sure if it fix your issue because I dont see your issue with your version
Operating System:
Platform: darwin
Arch: arm64
Version: Darwin Kernel Version 23.3.0: Wed Dec 20 21:31:00 PST 2023; root:xnu-10002.81.5~7/RELEASE_ARM64_T6020
Binaries:
Node: 20.10.0
npm: 10.2.3
Yarn: N/A
pnpm: 8.15.4
Relevant Packages:
next: 14.0.4
eslint-config-next: 14.0.4
react: 18.2.0
react-dom: 18.2.0
typescript: 5.4.3
Next.js Config:
output: N/A
but you are also not logged in na
I am logged in
so maybe thats why you getting 403
@Ray not sure if it fix your issue because I dont see your issue with your version
I also dont see a issue with version
@Ray Click to see attachment
what is true here?
ohh
you are showing me that your endpoint is being hit
why is not hitting for me then
I am deleting .next
and trying again
with adding {cache:'no-store'}
nope not working
still
giving 200 status
@Ray any idea what is happening
is it because of win11?
or vscode cache
I tried everything possible to not cache
but it is not hitting the frickin endpoint
@DhrishP1 but it is not hitting the frickin endpoint
const isAdmin = await fetch(http://localhost:3000/api/admin, {
cache: "no-store",
});
@DhrishP1 I am deleting .next
.
@DhrishP1 nope not working
.
@Ray try this maybe
yup deleting node_modules
the only thing I didnt try
I think its some dumb thing now
some real bug
or something
lemme try last time
I am so bored now
so dumb man so dumb
@Ray Thanks alot for trying
Means a lot
Literally cloned the code to help , thanks alot
❤️❤️
@DhrishP1 <@743561772069421169> Thanks alot for trying
did you find the issue?
@Ray did you find the issue?
Nope
btw, I have disabled the middleware on my side
maybe you could try it
But then auth won't work
Shouldn't have used v5 toolkit
just test if you hit the endpoint
a middleware issue
wow
@DhrishP1 a middleware issue
then check the logic
@DhrishP1 a middleware issue
  if (isApiAuthRoute || "/api/admin") {
    return null;
  }
@Ray ts if (isApiAuthRoute || "/api/admin") { return null; }
this is basically a temp fix
so it is a next-auth v5 beta issue
afterall
GREAT
nice
@DhrishP1 so it is a next-auth v5 beta issue
I don't think this is related to next-auth
@Ray I don't think this is related to next-auth
then why is it showing 200 when I am adding the middleware back
I checked the routes.ts and middleware.ts
because the request got redirect
seems alright to me
check the logic in the middleware
once again, you should call auth() instead
@Ray once again, you should call `auth()` instead
where? in the layout.ts or page.ts right?
Yea I am gonna do that
page.ts
or template.ts
maybe this is where it is redirecting , but I am loggedIn so shouldn't work
@Ray Yep
this was the issue
just console.logged and checked
it is redirecting here
yeah and that return 200 status
and couldn't hit /api/admin
weird thing
it is true at first
then getting false
before going into the function
lol
@Ray and couldn't hit /api/admin
yup
@Ray lol
this is a next-auth issue ig
lol
hopefully
weird issue
true at first then false
for a sec
@Ray can Nextjs components like layout.ts or page.ts can be async or not?
or do we have to call functions (async) for fetching api
@DhrishP1 <@743561772069421169> can Nextjs components like layout.ts or page.ts can be async or not?
it can be async, you are using async component with the AdminLayout
the isLoggedIn is getting false
when fetch is being called
rest it is working fine
its always true otherwise
import NextAuth from "next-auth";

import authConfig from "@/auth.config";
import {
  DEFAULT_LOGIN_REDIRECT,
  apiAuthPrefix,
  authRoutes,
  publicRoutes,
} from "@/routes";


const { auth } = NextAuth(authConfig);

export default  auth((req) => {
  const { nextUrl } = req;
  const isLoggedIn = !!req.auth;
  const isApiAuthRoute = nextUrl.pathname.startsWith(apiAuthPrefix);
  const isPublicRoute = publicRoutes.includes(nextUrl.pathname);
  const isAuthRoute = authRoutes.includes(nextUrl.pathname);
  if (isApiAuthRoute) {
    return null;
  }
  console.log(isLoggedIn)
  if (isAuthRoute) {
    if (isLoggedIn) {
      return Response.redirect(new URL(DEFAULT_LOGIN_REDIRECT, nextUrl))
    }
    return null;
  }
  console.log('2',isLoggedIn)
  if (!isLoggedIn && !isPublicRoute) {
    let callbackUrl = nextUrl.pathname;
    if (nextUrl.search) {
      callbackUrl += nextUrl.search;
    }

    const encodedCallbackUrl = encodeURIComponent(callbackUrl);

    return Response.redirect(new URL(
      `/auth/login?callbackUrl=${encodedCallbackUrl}`,
      nextUrl
    ));
  }

  return null;
})

// Optionally, don't invoke Middleware on some paths

// export default function middleware(req: any) {
//   return null;
// }

export const config = {
  matcher: ['/((?!.+\\.[\\w]+$|_next).*)', '/', '/(api|trpc)(.*)'],
}
const isLoggedIn = !!req.auth; this
any idea on why it is making it false?
when hitting a endpoint
the issue is the IsloggedIn variable
I checked it
that thing is getting false
once I call the endpoint
@DhrishP1 once I call the endpoint
did you mean once you call /api/admin and it become false?
thats the main issue
thats why we are getting redirected
@Ray try setup like this
is it v5?
@DhrishP1 is it v5?
yeah
@Ray yeah
yup same setup
auth.ts is diff
cuz of prisma and non-edge
it is mostly issue of beta ver of v
v5*
latest version , they might have fixed it
gotta work around for now
@DhrishP1 yup same setup
not same
@Ray not same
for auth.config.ts
I meant
the config for non-edge and edge is diffrerent
they use authorized callback
const isLoggedIn = !!auth?.user;
maybe you could try
const isLoggedIn = !!req.auth?.user;
I am also using authorized callback
authorized !== authorize
@Ray `authorized` !== `authorize`
I think it's because of prisma
I am using this setup
instead of the one you shared
but need to check
I am using jwt callback
to give me the token
to work with