Serverless Sign-In Solution Based on Next.js on CloudFare
How to set up your sign-in solution on CloudFare pages by using Next.js, NextAuth D1, and Prisma. The source code and the link to the working demo are provided.
Join the DZone community and get the full member experience.
Join For FreeIf you would like to run your own solution without any costs and get familiar with serverless architecture, I'd encourage you to look at CloudFare.
Recently, I tried to assemble all the pieces together to make the Next.js application authorization work on Cloudflare and faced a lot of issues. Provided examples on the official site and demos on other sources were working only partially. After some digging and combining the pieces together, it finally started working.
You could also look at the source code and working demo.
For the rest who would like to know what to do to get your own setup up and running, let's begin.
First, create your account on CloudFare. It's completely free and very straightforward to do.
Now, you can clone the demo project with:
git clone
You can find the instructions in the Readme.md
file and what you have to do there. There are multiple ways how you can run the project.
If you want to run it with hot reload, you'd better use:
pnpm run dev
But be aware that if the project runs with this command, it doesn't guarantee it will work on CloudFare. To be sure that when you deploy, it will work, you can verify it locally with:
pnpm run preview
But with this mode, you can't enjoy your hot-reloading capabilities and building time significantly longer. So, I would not use it during the active development.
In CloudFare, you can run your applications as Pages and also as Workers. I chose to run it as a Page because Workers have a limitation of 3 MB on a free tier. With the Next.js application, it's very easy to reach this threshold. It also means that if you'd like to add backend API, you have to create a Worker application and create a binding between Worker and Page.
Now, about the quirks you may come across when trying to create the same application from other sources:
In auth.ts
, you'll find an example to configure it as:
const authResult = async (): Promise<NextAuthResult> => {
return NextAuth({
providers: [
Resend({
apiKey: (await getCloudflareContext()).env.AUTH_RESEND_KEY,
from: (await getCloudflareContext()).env.AUTH_EMAIL_FROM,
}),
],
adapter: D1Adapter((await getCloudflareContext()).env.DB),
});
};
Notice the line:
D1Adapter((await getCloudflareContext()).env.DB),
This will not work!
The latest version of NextAuth doesn't allow to do it as it treats it as an invocation in the root of the file.
Also, be careful with getting the context. In the example above:
- For Workers, it is
getCloudflareContext()
. - For Pages, it is
getRequestContext()
.
You can't mix them; otherwise, it will be borked.
The next issue is with NextAuth when you deal with signing in the user and redirecting it to the page. I've seen many suggestions in StackOverflow, but what seems to work the best is:
try {
await signIn("credentials", {
email: formData.get("email") as string,
});
} catch (error) {
if (error?.hasOwnProperty("digest")) {
throw error;
}
}
What's going on here?
signIn
actually throws the exception always! It doesn't really matter if the user signed in successfully or not. But, to let the error propagate when the user signs in, it works well, and the page is redirected how it should.
In the case of failure we use an extra logic for that. As this is a server-side component, there are not many options how to display the error to users. I used the solution to pass the information via cookie, because useState
, useEfffect
, and other hooks work only for client-side components.
One more thing to be aware of: I was very surprised to see that it matters which package manager to use. When I used npm
, I've seen very weird errors. Also, do not mix invocation of different package managers — first pnpm
, then npm
, or yarn
. It can make your application not work after.
Happy coding, and let me know if you'd like to share with me your experience with this tech stack and the challenges on the way with it!
Opinions expressed by DZone contributors are their own.
Comments