NextAuth.js vs. Serverless Stack Authentication — A Side-by-Side Comparison | by Julien Bras | Nov, 2022

Comparing ease of implementation, deployment, and more

image by author

In a previous article, I explained how to use sst authentic Build to implement OAuth authentication workflow for your application.

next.jsThe React framework for production also provides a component called NextAuth.js Which can be used to implement such an authentication system. Let’s compare the two solutions!

sst Initially the backend is a framework designed to build serverless applications. I have already written several articles on this solution (Here And Here, For example). It also provides features for deploying web applications (for example, static site build), so it is advertised as a tool for building full-stack serverless applications.

certification The module is a dedicated set of components built by the SST team for implementing an authentication system inside your application. It works well with web applications like React apps.

next.js is probably the most well-known React-based framework available today, and has gained a lot of visibility over the past few years. Today with version 13, it is a truly full-stack framework solution with support for server-side rendering options and an API layer. You can check, for example, Theo Brown Video: Next.js is a backend framework Which is a good introduction to the backend part.

NextAuth.js There is a free library (not supported by Versailles) with the following motto: “Authentication for Next.JS.” It provides a built-in solution for implementing an authentication system for Next.js based on the OAuth protocol.

You know actors. Now, it’s time to move on to the comparative bullet points. Let’s fight 😇

Nowadays, authentication is not just email-password credentials. It’s more social logins like Google, Facebook, or GitHub. It’s more secure for the application developer (no more passwords to store!) and the application end-user (no new passwords to remember!). Let’s see what is supported by our two options.

First, SST certification is supporting offbeat today (Nov 2022) seven adapters: Google, GitHub, Twitch, Facebook, Magic Link, OAuth, and OIDC. The last two are generic adapters that can be used for any application supporting OAuth2 either OIDC, Finally, there is the option of making a custom adapter If anything doesn’t suit your needs. For example, in final articleI created a custom adapter to support SmugMug, which relies on the OAuth 1.0a protocol.

Supports more than NextAuth.js 20 providers Out-of-the-box: Classics like Google, Facebook, and GitHub are here, but there are more options than SST certification. there is also one E-mail provider (which can be compared to Magic Link One on SST certification) or a custom provider, eventually credit The provider is ideal if you need to log in via username, password, or other arbitrary credentials (for example, YubiKey).

There are many more out-of-the-box options that use NextAuth.js than SST Authentication. But both the solutions give you customization when needed.

authentication is a Serious Subject, and you don’t want to trust a system you don’t trust 100%. So it is important to understand how to implement the solution and how easily you can understand and improve it.

Let us have a look at the SST certification:

  • you must first add Auth build into your infrastructure stack (typically stacks/MyStack.ts file)
import  Auth  from "@serverless-stack/resources";

const auth = new Auth(stack, "auth",
authenticator:
handler: "functions/auth.handler",
,
);

auth.attach(stack,
api: myApi,
prefix: "/auth", // optional
);ty

  • then you can create a new serverless function src/functions/auth.ts which will be responsible for all authentication calls (authorize And callback End point for OAuth2, for example):
import  AuthHandler, GoogleAdapter  from "@serverless-stack/node/auth";

export const handler = AuthHandler({
providers:
google: GoogleAdapter(
mode: "oidc",
clientID: "XXXX",
onSuccess: async (tokenset) =>
return
statusCode: 200,
body: JSON.stringify(tokenset.claims()),
;
,
),
,
});

This example case (from authentic documentGoogle is building an authentication system based on Sign In. This will expose two endpoints:

  • /auth/google/authorize
  • /auth/google/callback
  • Finally, it is up to your frontend application (e.g. React) to redirect the user autorize Backend endpoint (this will start the OAuth2 flow).

Let’s zoom in on NextAuth.js now:

  • First, you need to install NextAuth.js in your Next.js project:
yarn add next-auth
  • Then you have to create a new API in your next project inside design pages/api/ folder. so create a file named pages/api/auth/[...nextauth].js with the following ingredients:
import NextAuth from "next-auth"
import GoogleProvider from "next-auth/providers/google"
export const authOptions =
// Configure one or more authentication providers
providers: [
GoogleProvider(
clientId: process.env.GOOGLE_ID,
clientSecret: process.env.GOOGLE_SECRET,
),
],

export default NextAuth(authOptions)

This API proxy endpoint is exactly equivalent to auth.ts Made for SST. Creating multiple endpoints will be taken care of by NextAuth.js authorize And callback To support OAuth2.

  • It is recommended to apply after SessionProvider at the top level of the application (in pages/_app.jsx,
import  SessionProvider  from "next-auth/react"
export default function App(
Component,
pageProps: session, ...pageProps ,
)
return (



)
  • And finally, use the dedicated methods provided by NextAuth.js to allow the end user to sign in or sign out:
import  useSession, signIn, signOut  from "next-auth/react"
export default function Component()
const data: session = useSession()
if (session)
return (
<>
Signed in as session.user.email



)

return (
<>
Not signed in



)

This article won’t delve into the implementation, but each solution provides a session mechanism for retrieving user data on the frontend and backend. It is also possible to prevent access for unauthenticated users.

To conclude on this aspect, both the solutions are simple enough that can be used by a frontend developer and do not require huge amount of code. The documentation provided is also very complete. it’s a draw!

After authentication is implemented, you may need to store some information related to each user. For example, a profile section needs to be maintained or any relevant information for your exact business case. Then both solutions come up with a solution for that.

For SST certification, it is quite natural to rely on a separate SST formulation, table, which relies on AWS DynamoDB. by applying onSuccess Available method in each adapter, it is possible to store user data in DynamoDB:

export const handler = AuthHandler({
providers: {
smugmug: SmugMugAdapter(
clientId: process.env.SMUGMUG_CLIENT_ID!,
clientSecret: process.env.SMUGMUG_CLIENT_SECRET!,
onSuccess: async (user: SmugMugUser) =>
const ddb = new DynamoDBClient();
await ddb.send(
new PutItemCommand(
TableName: Table.users.tableName,
Item: marshall(user),
)
);

return Session.parameter(
redirect: process.env.IS_LOCAL
? "http://127.0.0.1:3000"
: ViteStaticSite.site.url,
type: "user",
properties:
userID: user.userId,
,
);
,
),
},
});

taken from the example OAuth with Serverless using SST

With NextAuthjs, it is possible to implement adapter

Comment:NextAuthjs adapter is not the same as SST authentication adapter!

There are over ten options including DynamoDB, Firebase, Prisma, FaunaDB… Let’s zoom in on the DynamoDB adapter here:

  • Install the relevant adapters:
yarn add next-auth @next-auth/dynamodb-adapter
  • edit your existing api in pages/api/auth/[...nextauth].js,
import  DynamoDB  from "@aws-sdk/client-dynamodb"
import DynamoDBDocument from "@aws-sdk/lib-dynamodb"
import NextAuth from "next-auth";
import Providers from "next-auth/providers";
import DynamoDBAdapter from "@next-auth/dynamodb-adapter"

const config: DynamoDBClientConfig =
credentials:
accessKeyId: process.env.NEXT_AUTH_AWS_ACCESS_KEY as string,
secretAccessKey: process.env.NEXT_AUTH_AWS_SECRET_KEY as string,
,
region: process.env.NEXT_AUTH_AWS_REGION,
;

const client = DynamoDBDocument.from(new DynamoDB(config),
marshallOptions:
convertEmptyValues: true,
removeUndefinedValues: true,
convertClassInstanceToMap: true,
,
)

export default NextAuth(
providers: [
Providers.Google(
clientId: process.env.GOOGLE_ID,
clientSecret: process.env.GOOGLE_SECRET,
),
],
adapter: DynamoDBAdapter(
client
),
);

You will have more information about the adapter Here, Note that you will need to create the DynamoDB table before using this (NextAuth.js does not handle the creation of the resource).

Both solutions implement the option of storing information relative to the user. SST depends on constructs, and NextAuth depends on adapters. SST is a more integrated solution as it will handle resource creation (implicitly as infrastructure code). No clear winner here again!

Now it’s time to ship your application! How easy is the process for each solution? Let’s find it!

SST certification is a part of SST. This serverless framework is designed to be used with AWS. So it would be best if you rely on this specific cloud provider, but it has a dedicated CLI command to push your application. as DocumentThis command will send your application to sky cloud:

yarn deploy --stage prod

It is recommended to use a specific stage for a production environment because SST is designed to use multiple instances: when you develop on the application you can use a specific stage (such as Dev) with powerful are using live lambda development way.

With respect to NextAuth.js, you need to deploy a Next.js application. Here the short cut is to deploy your application Versailles, creator of Next.js. It has a generous free tier and features out of the box: automated deployment with GitHub, preview deployment, etc. But a Next.js application can be deployed to many other providers as well. For your own managed node server for serverless deployment, it’s up to you to choose the right one! View full list at Next.js documentation page,

Let’s say it is possible to deploy Next.js applications using SST 😅.
it depends on the setup serverless-next.js project and it is hidden behind the creation of the name NextJS Site, This can be a very efficient solution when you want to deploy your application on AWS environment (I use it for production workloads at my current company).

To conclude this section, SST is, by design, more restricted in deployment (AWS only). For Next.js, the classic way is to rely on Versal, but there are other options available (including SST on AWS itself).

By design it is not fair to compare tools that are not in the same category! But I think sometimes it is useful to compare a specific feature (authentication here) as the implementation in both solutions is very comparable.

SST is a really good choice when you need to build an application that needs to depend on multiple AWS services; It is possible to define and then consume infrastructure using code QueueOne Bucketand a database, to name a few of the available constructions. This is the most detailed solution here. Read my introduction to SST here: SST is the most underrated serverless framework you need to find

NextAuth.js is just a library, and with this solution it is fast to add an authentication layer to an existing Next.js application. This is the most integrated solution here.

I recommend playing with the two solutions here and give me your feedback Twitter (If it’s still up and running when you read this!)

Leave a Reply