Secure your NextJS Apps with Azure AD and NextAuth (Part 5)

Securing your API Routes with NextAuth

Dewaun Ayers
3 min readMar 5, 2023

Disclaimer: This is part 5 of a 7 part tutorial. Click the below link to go back to Part 1 to learn more about the intent of this tutorial.

Part 1 — Introduction and “What is an Identity Provider?”

Or go back to Part 4 — Using NextAuth inYour Application which explains the usage of NextAuth and the components we’ve created up to now.

NextAuth gives us a convenient way to lock down our Next.js API routes. Let’s modify the pages/api/hello.ts API route to only return a valid response if we are logged in.

// pages/api/hello.ts
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import type { NextApiRequest, NextApiResponse } from "next";
import { getServerSession } from "next-auth/next";
import { authOptions } from "./auth/[...nextauth]";

type Data = {
data?: any;
error?: string;
};

export default async function handler(
req: NextApiRequest,
res: NextApiResponse<Data>
) {
const session = await getServerSession(req, res, authOptions);

if (session) {
res.send({
data: {
content:
"HELLO. You can view this protected content because you are signed in!",
},
});
} else {
res.send({
error:
"Sorry... but you can't sit with us...",
});
}
}

The getServerSession function from next-auth/next gives us a way to verify that the user session is valid on the server side. If it’s valid, we return a message telling the user so. If it isn’t then we can return an error message.

Let’s test this out by adding a button to the UI that greets us if we are logged in.

In the app directory create a new React client component called GreetMe.tsx and add the following code

"use client";
import { useState } from "react";

export const GreetMe = () => {
const [greeting, setGreeting] = useState("");

async function onClick() {
const response = await fetch("/api/hello");
const json = await response.json();
const { data, error } = json;
setGreeting(data?.content ?? error);
}

return (
<div>
{greeting && <p>{greeting}</p>}
<button onClick={onClick}>Greet Me!</button>
</div>
);
};

This component uses fetch to request data from the /api/hello API route. It then sets the result in the greeting state variable and updates the UI accordingly.

Import the new component into the app/page.tsx file and place it below the LoginButton component.

Click Greet Me and see which message you receive.

Here’s what the UI should look like when you are signed in:

Here’s what the UI should look like when you are not signed in:

Great! Now you’ve secured your API Routes! This is awesome for local development but the real test comes when we deploy our application to AWS. Let’s do that in Part 6.

What’s next?

Part 6 — Deploying with Serverless Stack
Part 7 — Third-Party Authentication and Authorization with AWS AppSync

My goal is to provide content that leaves readers with a bit more knowledge than they started with.

If this tutorial helped you in anyway please leave a clap or two! If you have any questions or I got something wrong, leave a comment and let me know how I can improve!

--

--

Dewaun Ayers
Dewaun Ayers

Written by Dewaun Ayers

I'm a Frontend Dev living in Melbourne, Australia and studying Computer Science. I love anything to do with web tech and am constantly trying to learn more!

No responses yet