Most production apps need auth, and the de facto open source solution for Next.js is NextAuth, now known as Auth.js.
Version 5 of Auth.js, as of writing, is in beta. (The “Next” was dropped because Auth.js can be used with a number of other frameworks, such as SvelteKit) There’s been a lot of grumbling about adopting the stable NextAuth v4, so you can imagine that many have struggled with v5.
And that’s why I created this starter — to make setting up Auth in your Next.js app a little easier. Besides showing you how to set up Auth with most common use cases, (e.g. middleware, edge compatibility), I’ll also go over some best practices & personal recommendations in this post.
Explaining “the Why”
The Auth Strategy
For most apps, a combination of two strategies should be used. The session should be managed with a JWT, but user details & data should be stowed away in a database.
This way retrieving user details remains smooth, quick, and not resource intensive. (If you only use JWT, you can’t do any credentials-based auth. Choose a database-only strategy, and you set yourself up for poor performance, or a huge bill for the large amount of requests).
Edge Compatibility
Nodemailer and bcrypt, used for sending out password reset emails and hashing passwords, respectively, aren’t edge compatible. They are built for Node, and throw out errors when used in middleware, which runs on edge.
To fix this, I split the auth configuration into two, as the official docs recommend. The minimal config.ts
which lacks the Credentials or Email strategy is used for middleware, while the full index.ts
file of the auth directory (where config.ts is spread) is used for everything else.
Setting it Up
Check out the env.example file for all the env variables you need. Basically, it’s only two things that require a little work - the database connection URL and email credentials. Aside from that, an Auth Secret and Auth URL (needed in Development only) is required by Auth.js.
When you run the development server, navigate to /login
, /signup
to create an account, and you’ll be redirected to a members only page, /account
to see the magic.
Closing Notes
I’d like to mention that I’m not a huge fan of starters. That’s why I kept in fairly minimal, leaving the default create-next-app boilerplate styles, page, and layout. The login, signup, and account settings pages are also minimally styled—with just enough tailwind classes to be usable.
If you have any questions about the starter, feel free to open an issue or start a discussion on the Repo. Hope it takes the headache out of Auth.js!