Opting for Mysql over MongoDB as the provider in Next.js with Next-auth

Exploring the Next.js framework for the first time, I've dived into using Next-auth to handle sign-up/login functionality based on the provided documentation.

My experience so far has been smooth, especially with the MongoDB provider as recommended in the Next-auth documentation.

To send email notifications post-user login, I have integrated SendGrid using the URL sourced from MongoDB within my .env.local file:

EMAIL_SERVER_HOST=smtp.sendgrid.net
EMAIL_SERVER_PORT=587
EMAIL_SERVER_USER=apikey
EMAIL_SERVER_PASSWORD=<password>
EMAIL_FROM=<email>
MONGODB_URI=mongodb+srv://mdb:<password>@cluster0.uetg3.mongodb.net/learnnextauth?retryWrites=true&w=majority

In addition, I made modifications in pages/api/auth/lib/mongodb.js:

import { MongoClient } from "mongodb"

const uri = process.env.MONGODB_URI
const options = {
useUnifiedTopology: true,
useNewUrlParser: true,
}

let client
let clientPromise

if (!process.env.MONGODB_URI) {
throw new Error("Please add your Mongo URI to .env.local")
}

if (process.env.NODE_ENV === "development") {
if (!global._mongoClientPromise) {
client = new MongoClient(uri, options)
global._mongoClientPromise = client.connect()
}
clientPromise = global._mongoClientPromise
} else {
client = new MongoClient(uri, options)
clientPromise = client.connect()
}
export default clientPromise

Utilizing the EmailProvider from Next-auth and setting up configuration details in pages/api/auth/[...nextauth].js:

import EmailProvider from "next-auth/providers/email";
import NextAuth from "next-auth/next";
import { MongoDBAdapter } from "@next-auth/mongodb-adapter"
import clientPromise from "./lib/mongodb"

export default NextAuth({
adapter: MongoDBAdapter(clientPromise),
providers: [
    EmailProvider({
      server: {
        host: process.env.EMAIL_SERVER_HOST,
        port: process.env.EMAIL_SERVER_PORT,
        auth: {
          user: process.env.EMAIL_SERVER_USER,
          pass: process.env.EMAIL_SERVER_PASSWORD
        }
      },
      from: process.env.EMAIL_FROM
    }),
  ],
})

Furthermore, I implemented a component in pages/index.js to control authenticated sessions:

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} <br/>
  <button onClick={() => signOut()}>Sign out</button>
</>
}
return <>
Not signed in <br/>
<button onClick={() => signIn()}>Sign in</button>
</>
}

Additionally, in pages/_app.js code snippet:

import { SessionProvider } from "next-auth/react"

export default function App({
Component,
pageProps: { session, ...pageProps },
}) {
return (
<SessionProvider session={session}>
  <Component {...pageProps} />
</SessionProvider>
)
}

Lastly, settings from package.json were tweaked accordingly:

{
"name": "auth-v4",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"@next-auth/mongodb-adapter": "^1.0.1",
"@popperjs/core": "^2.11.2",
"bootstrap": "^5.1.3",
"mongodb": "^4.3.1",
"next": "12.0.10",
"next-auth": "^4.2.1",
"nodemailer": "^6.7.2",
"react": "17.0.2",
"react-dom": "17.0.2",
"typescript": "^4.5.5"
},
"devDependencies": {
"eslint": "^8.9.0",
"eslint-config-next": "12.0.10"
}
}

Looking to integrate MySQL instead of MongoDB due to specific requirements, here are some queries that I seek guidance on:

1- How can I correctly configure the MySQL URL within ".env.local"?

2- Are there any pre-built providers available for MySQL like the MongoDB adapter mentioned in Next-auth's documentation?

3- Besides "mysql" and "serverless-mysql", are there any additional dependencies required for MySQL integration?

Note: I am relying on MySQL Workbench for database management.

Your detailed assistance is highly appreciated as I strive to grasp the concepts thoroughly, given my novice status in the Next.js framework.

(Feel free to seek clarification if any part of my query seems unclear, considering English isn't my native language)

Thank you in advance for your support.

Answer №1

Indeed, there seems to be a lack of examples for setting up mySQL with NextAuth.

You could experiment with the configuration in your [...nextauth].js file...

providers: [...],  
    adapter: TypeORMLegacyAdapter({
    type: 'mysql',
    database: process.env.MYSQL_DATABASE,
    username: process.env.MYSQL_USER,
    password: process.env.MYSQL_PASSWORD,
  }),

After that, make sure to add your variables to the .env.local file...

MYSQL_HOST = 127.0.0.1
MYSQL_PORT = 3306
MYSQL_DATABASE = xxxxx
MYSQL_USER = xxxxxx
MYSQL_PASSWORD = xxxxx

I hope this information proves useful. If you took a different approach, feel free to share it with us.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Arrow indicating the correct direction to expand or collapse all items with a single click

I have successfully implemented the "expand/collapse all" function, but I am facing an issue with the arrow direction. The arrows are not pointing in the correct direction as desired. Since I am unsure how to fix this problem, I have left it empty in my co ...

How to retrieve specific JSON data from a field in MYSQL database

I need to retrieve data from the reviewed_by table where the "company" is "AAA" and the "review" is "Need Review". Here is the structure of the MySQL table : +-----------+ | DATA_TYPE | +-----------+ | text | +-----------+ +-------------------------+ ...

Ways to disable an AJAX loading animation

In my current script, I am loading external content using the following code: <script type="text/javascript"> var http_request = false; function makePOSTRequest(url, parameters) { // Code for making POST request } function alertContents() { ...

Generating a header each time a table is printed across multiple pages

A table has been created in a webform using C#. The goal is to only print the table when the user clicks the print button on the webform. Javascript has been implemented in ASP.NET to only print the content within a specific div. While this method works, ...

Is there a way to exclude the element from being displayed when using ngIf in AngularJS?

Is there a way in Angular to conditionally add an element to the DOM without having it always added, even when its evaluation is false? I am looking for an alternative method to ngIf. ...

A guide on how to alternate between ng-hide and ng-show using separate controllers by utilizing a shared factory toggle state instance

Using Angular 1.x, I have implemented two controllers where I want to display controller_2 if controller_1 is hidden. To achieve this, I am utilizing a factory method. Here is the snippet of my HTML code:- <div ng-controller="controller_1 as c1" ng- ...

Having trouble retrieving data in Angular from the TypeScript file

demo.component.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-demo', templateUrl: './demo.component.html', styleUrls: ['./demo.component.css'] }) ...

What's the best way to capture an element screenshot using JavaScript?

I'm working on developing a unique gradient selection application. One of the exciting features I would like to incorporate is the ability for users to save their chosen gradients as digital images (.jpg format) directly onto their computers. When the ...

Include the component with the function getStaticProps loaded

I am currently working on a project using NextJs and I have created a component to load dynamic data. The component works fine when accessed via localhost:3000/faq, but I encounter an error when trying to import the same component into index.js. It seems l ...

How to utilize a PHP array within a Vue.js template

I have been exploring the realms of Laravel and vue.js recently and have encountered a challenge. Within my Laravel model, I have a PHP method that retrieves data from a database and organizes it into objects stored in an array. Now, my goal is to access t ...

Tips for retrieving a child component's content children in Angular 2

Having an issue with Angular 2. The Main component displays the menu, and it has a child component called Tabs. This Tabs component dynamically adds Tab components when menu items are clicked in the Main component. Using @ContentChildren in the Tabs comp ...

Issue encountered while deploying Next.js on Firebase hosting - Incorrect CPU value provided

I encountered an issue while attempting to deploy a Next.js 13 application on Firebase Hosting using firebase-tools. Error Message: HTTP Error: 400, Could not create Cloud Run service ssrlyeanabot. spec.template.spec.containers.resources.limits.cpu: Inval ...

What is the process for invoking a server-side Java function from HTML with JavaScript?

Can someone help me figure out the best way to invoke a Java method from HTML (I'm working with HTML5) using JavaScript? I attempted using Applets but that approach didn't yield any results. My goal is to extract the value from a drop-down menu i ...

Passing in additional custom post data alongside serializing with jQuery

function MakeHttpRequest( args ) { var dataToSend = "?" + $("form[name=" + args.formName + "]").serialize(); $.ajax({ type: "POST", url: args.url + dataToSend, data: { request: args.request }, su ...

Analyze the information presented in an HTML table and determine the correct response in a Q&A quiz application

I need to compare each row with a specific row and highlight the border accordingly: <table *ngFor="let Question from Questions| paginate: { itemsPerPage: 1, currentPage: p }"> <tr><td>emp.question</td></tr> <tr> ...

The asynchronous callbacks or promises executing independently of protractor/webdriver's knowledge

Could a log like this actually exist? 07-<...>.js ... Stacktrace: [31m[31mError: Failed expectation[31m [31m at [object Object].<anonymous> (...06-....js)[31m[31m[22m[39m It seems that something is failing in file -06- while I am processin ...

Should reports be created in Angular or Node? Is it better to generate HTML on the client side or server side

I have a daunting task ahead of me - creating 18 intricate reports filled with vast amounts of data for both print and PDF formats. These reports, however, do not require any user interaction. Currently, my process involves the following: The index.html ...

I have successfully tested my login/sign-up API locally, but after deploying it, the functionality seems to be broken. I attempted to test it using Postman, but it appears to be stuck

As mentioned in the query, the code works seamlessly in my local environment but fails to function in production. I am utilizing mongodb/express__NodeJs for this project. Below are the key excerpts of the code: Server.js const express = require('expr ...

What is the best way to pause function execution until a user action is completed within a separate Modal?

I'm currently working on a drink tracking application. Users have the ability to add drinks, but there is also a drink limit feature in place to alert them when they reach their set limit. A modal will pop up with options to cancel or continue adding ...

Forwarding information and transferring data from a Node server to ReactUIApplicationDelegate

I am currently working on a NodeJS server using Express and React on the front-end. I am trying to figure out how to send data from the server to the front-end without initiating a call directly from the front-end. The usual solutions involve a request fro ...