DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • How to Build a Full-Stack App With Next.js, Prisma, Postgres, and Fastify
  • Lessons Learned Moving From On-Prem to Cloud Native
  • Scaling in Practice: Caching and Rate-Limiting With Redis and Next.js
  • Auto-Instrumentation in Azure Application Insights With AKS

Trending

  • A Guide to Container Runtimes
  • Create Your Own AI-Powered Virtual Tutor: An Easy Tutorial
  • The Modern Data Stack Is Overrated — Here’s What Works
  • Unlocking AI Coding Assistants Part 2: Generating Code
  1. DZone
  2. Coding
  3. JavaScript
  4. Serverless Sign-In Solution Based on Next.js on CloudFare

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.

By 
Bogdan Nechyporenko user avatar
Bogdan Nechyporenko
DZone Core CORE ·
Mar. 19, 25 · Tutorial
Likes (1)
Comment
Save
Tweet
Share
3.9K Views

Join the DZone community and get the full member experience.

Join For Free

If 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.

Note to all impatient readers

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.

Number one on the list — check!

Now, you can clone the demo project with: 

Plain Text
 
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:

Plain Text
 
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:

Plain Text
 
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:

Uh oh!

In auth.ts, you'll find an example to configure it as:

TypeScript
 
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:

Plain Text
 
D1Adapter((await getCloudflareContext()).env.DB),


This will not work!

Oof, what a bummer!

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.

Oof!

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:

TypeScript
 
try {
  await signIn("credentials", {
    email: formData.get("email") as string,
  });
} catch (error) {
  if (error?.hasOwnProperty("digest")) {
      throw error;
   }
}


What's going on here? 

Hmm...

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!

What did you think of my article?

Next.js application Npm (software)

Opinions expressed by DZone contributors are their own.

Related

  • How to Build a Full-Stack App With Next.js, Prisma, Postgres, and Fastify
  • Lessons Learned Moving From On-Prem to Cloud Native
  • Scaling in Practice: Caching and Rate-Limiting With Redis and Next.js
  • Auto-Instrumentation in Azure Application Insights With AKS

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!