Incorporating a user ID (foreign key) into a MySQL table using NextJS and Prisma

Currently, I am in the process of developing an online recipe platform that allows users to log in and share their recipes. The technology stack I am using includes NextJS, Prisma, and MySQL DB. User authentication is handled with NextAuth and a credentials provider utilizing usernames and passwords. My challenge lies in establishing a foreign key constraint between the users table and recipe tables by linking them through a userID. Each recipe should be associated with a specific user, but I am unsure how to retrieve the current session data containing only the username and then relate it to the user's auto-incremented userID stored in Prisma. Is there any feasible method to link a user to a recipe solely based on next auth credentials (username and password)?

https://i.stack.imgur.com/zPQ1l.png

https://i.stack.imgur.com/aNofp.png

Answer №1

If you want to personalize what information is added to the JWT and session in your NextAuth setup, you have the ability to do so.

Below is an example of how you can insert the userId into both the JWT and session:

import NextAuth from 'next-auth'
import Providers from 'next-auth/providers'
import Adapters from 'next-auth/adapters'
import prisma from '../../../db' // your prisma client

export default NextAuth({
  providers: [
    Providers.Credentials({
      // Your credentials provider configuration
    })
  ],
  adapter: Adapters.Prisma.Adapter({ prisma }),
  secret: process.env.SECRET,
  callbacks: {
    async jwt(token, user) {
      // Initial sign in
      if (user) {
        token.id = user.id
      }
      return token
    },
    async session(session, token) {
      // Add property to session, like `userId`
      session.userId = token.id
      return session
    }
  }
})

In your API routes, you can now access `userId` directly from the session:

import { getSession } from "next-auth/client";

export default async (req, res) => {
  const session = await getSession({ req });
  console.log(session.userId);  // you can use this id to link the user with the recipe
  // your code here
}

This implementation ensures that whenever a user logs in, their userId will be included in both the JWT and session data.

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

Issue with unnamed column in Pandas dataframe prevents insertion into MySQL from JSON data

Currently, I am working with a large JSON file and attempting to dynamically push its data into a MySQL database. Due to the size of the JSON file, I am parsing it line by line in Python using the yield function, converting each line into small pandas Data ...

Performing a search in Django using raw MySQL commands

I am currently in the process of developing a custom search engine that includes 4 search fields, aiming to search within a MySQL table. This snippet from my views.py covers the search functionality, pagination, and listing of the entire table data. def ...

Transform 31 July 2003 formatting into a MySQL Date Object

I'm currently utilizing Python 3.5 My query is in the format 31-Jul-03. Now, I am looking to convert it to 2003-07-31 or a compatible format for MySQL Date object. I could manually parse this query, but that would be somewhat cumbersome and others ...

Encountering an error of "FAIL: NoSectionError: No section: 'default'" when attempting to connect Robot Framework with MySQL

After attempting to connect with a MySQL database using my code, I encountered an error message stating "FAIL: NoSectionError: No section: 'default'". I am seeking guidance on how to establish a successful connection with a MySQL database from wi ...

Encountering a MySQLdb error in Python while attempting to modify a table structure

I need some assistance with updating a database, as I am struggling to find the correct syntax online. The specific line causing an error is: cur.execute("ALTER TABLE Units ADD FOREIGN KEY(pnid), REFERENCES Basic(pnid)) ") The error message reads: Pr ...

Retrieving table names while querying database in Python Flask

Recently, I made the switch from PHP to Flask after three years. I successfully connected to my local server and database, and managed to query data from it and display it on screen. However, when attempting to work on a small REST API project, I ran int ...

Struggling with the conversion of string data to integer, float, or decimal format in order to create plots using matplotlib

Having extracted data from a SQL database table, I am encountering persistent challenges in plotting a graph between two variables due to conversion issues with data types. I initially converted a list to a str, and now I'm attempting to further conve ...

How can I enhance speed and efficiency when transferring data into MySQL databases?

I am currently developing a website using Django and MySQL (MyISAM) as the backend. The database data is being imported from multiple XML files processed by an external script and output as a JSON file. Whenever a new JSON file differs from the previous on ...

I am encountering the issue where Prisma client python consistently notifies me that my client has not been generated, despite the fact that I have already executed the necessary

After setting up Prisma Client Python and SQLite to create a database for my program successfully, I encountered an issue when trying to run my program. Despite ensuring that everything was installed correctly and running commands like "prisma generate" an ...

Access denied for user: MySQL encountered an ERROR 1045 (28000) which prevented the user

My attempt to connect a readonly MySQL-DB to my Django WebAPP has encountered a persistent error. Whether using Django, MySQL-Workbench, or MySQL-Shell, the outcome remains constant: ERROR 1045 (28000): Access denied for user 'db-foo-read'@' ...

Using Python to Execute MySQL Date Range Queries

Running a loop query for multiple date ranges: con = MySQLdb.connect(host='xxx.com', port=3306,user='user', passwd='pass', db='db') intervals = 10 precision = 1 dateChunks = list() for i in range(0,intervals,preci ...

Setting the Host Parameter during the creation of a user in a Rackspace Cloud Database Instance

Rackspace has recently implemented a new feature that allows users to select specific cloud servers as hosts when creating a user in a cloud database instance. This ensures that the specified user can only be accessed from those designated cloud servers. ...

Django does not support CORS headers

As I work on building an API in Django and utilizing Next.js for the frontend, I consistently encounter an issue when trying to communicate between the backend and frontend. The console displays the following message: Access to XMLHttpRequest at 'http ...

Utilizing MySQL encoding in Python

Can someone help me with an issue related to saving a string in a MySQL database using Python? When trying to save the string, I encounter the following error: File ".smart.py", line 51, in (number, text, 'smart', 'u') Unicod ...

Guide to integrating MPA frontend with SSR backend using Next.js?

I recently purchased an MUI template for my project. Utilizing React with Next.js and Flask as the backend, the MUI template functions as a Multiple-Page Application. In the past, I have utilized Flask for a Single Page Application by simply using return s ...