Encountering an Issue when Registering New Users in Database using Next.js, Prisma, and Heroku

Currently, I am immersed in my inaugural full-stack app development project, which is aligning with an online course. Unfortunately, I have encountered a major stumbling block that has persisted despite hours of troubleshooting. The issue arises when I try to add a new user to a Postgres DB using the command line interface.

import bcrypt from 'bcrypt'
import jwt from 'jsonwebtoken'
import cookie from 'cookie'
import { NextApiRequest, NextApiResponse } from 'next'
import prisma from '../../lib/prisma'

export default async (req: NextApiRequest, res: NextApiResponse) => {
    const salt = bcrypt.genSaltSync()
    const { email, password } = req.body

    let user

    try {
        user = await prisma.user.create({
            data: {
            email,
            password: bcrypt.hashSync(password, salt),
        },
      })
    } catch (e) {
      res.status(401)
      res.json({ error: 'User already exists' })
      return
    }

    const token = jwt.sign(
    {
      email: user.email,
      id: user.id,
      time: Date.now(),
    },
      'hello',
      { expiresIn: '8h' }
    )

  res.setHeader(
    'Set-Cookie',
    cookie.serialize('TRAX_ACCESS_TOKEN', token, {
      httpOnly: true,
      maxAge: 8 * 60 * 60,
      path: '/',
      sameSite: 'lax',
      secure: process.env.NODE_ENV === 'production',
    })
  )

  res.json(user)
}

To attempt adding the user, I used the following command through HTTPie:

http POST :3000/api/signup <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7a1f171b131647123a1254191517">[email protected]</a> password=abcabc

Initially, there was an error regarding the data attribute, which got resolved post-running 'prisma generate'.

Now, the persistent error message states: User already exists.

However, upon checking the Prisma Studio in the Users table, it's clear that there isn't any newly created user present.

Response received:

HTTP/1.1 401 Unauthorized
Connection: keep-alive
Content-Length: 31
Content-Type: application/json; charset=utf-8
Date: Sun, 05 Jun 2022 19:57:59 GMT
ETag: "1f-lFUySNKwX3L5eGEwGcNcUoVKWhE"
Keep-Alive: timeout=5
Vary: Accept-Encoding

{
    "error": "User already exists"
}

This excerpt shows my schema.prisma file structure:

// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema

generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider          = "postgresql"
  url               = env("DATABASE_URL")
  shadowDatabaseUrl = env("SHADOW_DATABASE_URL")
}

model User {
  id        Int        @id @default(autoincrement())
  createdAt DateTime   @default(now())
  updatedAt DateTime   @updatedAt
  email     String     @unique
  firstName String?
  lastName  String?
  password  String
  playlists Playlist[]
}

model Song {
  id        Int        @id @default(autoincrement())
  createdAt DateTime   @default(now())
  updatedAt DateTime   @updatedAt
  name      String
  artist    Artist     @relation(fields: [artistId], references: [id])
  artistId  Int
  playlists Playlist[]
  duration  Int
  url       String
}

model Artist {
  id        Int      @id @default(autoincrement())
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
  songs     Song[]
  name      String   @unique
}

model Playlist {
  id        Int      @id @default(autoincrement())
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
  name      String
  songs     Song[]
  user      User     @relation(fields: [userId], references: [id])
  userId    Int
}

Answer №1

After making some adjustments in my middleware.ts file, I managed to solve the issue by adding the prefix ${origin} as shown below:

import { NextResponse } from 'next/server'

const signedinPages = ['${origin}/', '${origin}/playlist', 
'${origin}/library']

export default function middleware(req) {
  if (signedinPages.find((p) => p === req.nextUrl.pathname)) {
    const token = req.cookies.MMA_ACCESS_TOKEN

    if (!token) {
      return NextResponse.redirect('${origin}/signin')
    }
  }
}

Additionally, I updated my HTTPie request to

http POST :3000/api/signup <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="52373f333b3e6f3a12e39162433fa1c2[email protected]</a> password=abcabc firstName=Eric lastName=Bell

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

In JavaScript, when using the fetch function with JSON, it is possible to skip the

Here's an example of fetching review data from within a 'for loop': fetch('https://api.yotpo.com/products/xx-apikey-xx/{{product.id}}/bottomline') In this case, some products may not have reviews and will return a 404 response. Th ...

Utilizing the default event object in ag-Grid's event methods with JavaScript

I am a newcomer to ag-grid and I need help with calling event.preventDefault() in the "cellEditingStopped" grid event. Unfortunately, I am struggling to pass the default JavaScript event object into it. Is there a way to make this work? Additionally, I al ...

Using multiple main.js files with RequireJs in Play Framework 2.1.1 Java: A step-by-step guide

While working on a single-page app with AngularJs + RequireJs in Play Framework 2.1.1, I encountered an issue regarding the structure of my application. The project consists of two main sections - an admin dashboard and a normal website - both housed withi ...

Scope binding is successful, but accessing the array is only possible after adding an Alert() function

Within my Angular controller, I'm utilizing the SharePoint JavaScript Object Model to fetch data from the Taxonomy (term store). Due to SharePoint's JSOM not being a conventional Angular function that can be easily understood by the scope, I util ...

Guide for setting up multiple checkbox event listeners with jQuery

I currently have 2 checkboxes on my form: <form action=""> <input id="bikeCheckbox" type="checkbox" name="bikeCheckbox" value="Bike">I own a bike<br> <input id="carCheckbox" type="checkbox" name="carCheckbox" value="Car">I ...

Automatically compile files while performing an npm install or update

I am looking for a way to automatically compile my TypeScript code into JavaScript when another project requires it. For example, when a project runs npm install or updates with my project as a dependency, I want a specific command to be executed after all ...

How to retrieve an object's property within a component

Currently, my goal is to retrieve the email property from the user object {"name":"test", "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="582c3d2b2c182c3d2b2c7620">[email protected]</a>"} I want to achie ...

Infinite scrolling with Jquery: Loading dynamic content seamlessly from external websites

Hey there! I recently started using this cool jQuery plugin called jquery-endless-scroll. Here's a snippet of my code: $(function() { $('#list').endlessScroll({ pagesToKeep: 10, fireOnce: false, insertBefore: "#list div:first ...

You can use jQuery AJAX to submit two forms' data simultaneously in just one submission

I am looking to submit two sets of form data with just one click. <form id="form1"> <input type="text" name="name"> <input type="submit" value="Submit"> </form> <form id=&quo ...

Attempting to adjust the width of a text animation loaded with jQuery using Textillate, but encountering difficulties

I found a captivating animation on this website: http://codepen.io/jschr/pen/GaJCi Currently, I am integrating it into my project. #content { position: relative; margin-left: auto; margin-right: auto; width: 1000px; height: 700px; } ...

What is the best way to ensure that text fields remain hidden upon page load until the appropriate drop down option is chosen?

Is it possible to initially hide text fields and only reveal them when a specific drop down option is selected? The current JavaScript code somewhat achieves this, but I would like the input fields to remain hidden by default. <script language=" ...

Method for creating a randomized layout grid in MaterialUI where each row contains a total of three columns

In the process of developing a React application that interacts with the reddit api and oAuth. Utilizing MaterialUI, I am currently experimenting with the Component to create a 3 column grid of images with dynamically generated column widths, maxing out a ...

How to programmatically clear an input field in Angular using Bootstrap's typeahead feature

My current setup involves utilizing a form to populate a list displayed alongside the form. The markup looks like: <form name="stateForm"> <input type="text" ng-model="model.name" typeahead="state for state in states | filter:$viewValue"> ...

Javascript puzzle - I have 99 obstacles

...but a malfunction isn't one. Hey there, I am new to learning so I apologize for the seemingly simple question. I'm experimenting with a theoretical logic statement that would work using javascript. For instance: if (issues == 99) { malfunct ...

Submitting an image from React and Redux to the backend: A comprehensive guide

I'm currently working with the MERN stack and facing an issue while trying to upload an image in the front end (react) and then access it in the backend (express, nodejs) for later storage. Despite using multer, I keep encountering 'undefined&apo ...

Exploring Handlebars.js: Understanding the Scope of Global Contexts

If I have a static list of cached users within my application under App.Users, there will likely be various instances where I need to display the list of users. Typically, I would just pass the list along with the context to the template. var tmpl = Handl ...

The width of the Bootstrap row decreases with each subsequent row

I'm having trouble understanding this issue, as it seems like every time I try to align my rows in bootstrap, they keep getting smaller. Can anyone point out what mistake I might be making? ...

Invoking code behind functions through ajax requests to dynamically display items one by one

I'm currently working with calling code behind functions from an ajax call. I have recently developed a method called Post, which returns a list of values. My goal is to verify these values from the client side by displaying them in an alert message. ...

What is the best way to send a string parameter from an Angular UI to a Node.js backend?

My goal is to transfer a string value from an Angular UI to a Node.js backend API, which will then search in MongoDB using the provided string value as shown below. I am attempting to receive input in enteredValue and pass it on to the http.get call as pa ...

What steps do I need to take to enable basic authentication for my PHP app on Heroku?

I need help enabling basic authentication for my simple PHP application hosted on Heroku's Cedar Stack. I am unsure if .htaccess / .htpasswd is supported in this environment. Can someone guide me on how to activate basic auth? ...