Next.js Discord

Discord Forum

how to secure my api's?

Answered
Waterman posted this in #help-forum
Open in Discord
Avatar
In a video I have been watching a little bit, this was his setup (almost)
  const session = await getServerSession(req, res, authOptions);
  if (!process.env.EMAILS?.includes(session?.user?.email)) {
    throw "Not Admin";
  }


and I basically have a lot of different sort of routes that looks like this, both get, put, post etc
export const PUT = async (req: NextRequest, res: Response) => {
  const body: kropp = await req.json();

  const {
    namn,
    fulltNamn,
    beskrivning,
    his

**More Code...**


but is there a go to method of doing this? because as you can see i am using next auth and I have therefore access to the session, how can i easily restrict these api ,or what every they are called, so that no other than the logged in user can do the request...

I appreciate all help 🙂
Answered by Waterman
I now tried this:
  const session = await getServerSession(authOptions);

  if (!session) {
    throw "Not Admin";
  }

It seems to be working
View full answer

3 Replies

Avatar
I also tried
  const { data: session, status } = useSession();

  if (status === "unauthenticated") {
    throw "Not Admin";
  }

but I got: Error: React Context is unavailable in Server Components
Avatar
I also tried :
 const token = await getToken({ req });

  if (token) {
    // Signed in
    console.log("JSON Web Token", JSON.stringify(token, null, 2));
  } else {
    // Not Signed in
    throw "Not Admin";
  }

but then I just got "not Admin" all the time even when signed in
Avatar
I now tried this:
  const session = await getServerSession(authOptions);

  if (!session) {
    throw "Not Admin";
  }

It seems to be working
Answer