Next.js Discord

Discord Forum

all logs show success but db doesn't update through the app.

Answered
West African Lion posted this in #help-forum
Open in Discord
West African LionOP
I have no idea if this even is a nextjs issue but:
I have a db which has a table called users, when i login with clerk, it makes a user. after login, the website takes the user to /onboarding where the user has to enter additional information like phone number, postcode and "about me." on submit, the db should be updated with the new details, for the same user, on the same users table. but it is not happening.

it does work when i update the db using postman

I have taken logs from the frontend and the backend with all returning status 200 with all the right details in json format. the db connection is working as well, checked with a simple GET API route and by running pnpm prisma studio. The status 200 logs:
Server: User ID from Clerk session (currentUser): user_2zPQd2ZhtqDzxIU7NU2s45utyRs
Server: User ID from form data (validatedData): {
  firstName: 'Lama',
  lastName: 'Baioi',
  postcode: 'BL1 3BH',
  email: 'mansoor.eb@gmail.com',
  phoneNumber: '0753791889',
  aboutMe: 'FIRST NAME LAST NAME'
}
Server: Attempting to update DB for ID: user_2zPQd2ZhtqDzxIU7NU2s45utyRs
prisma:query SELECT 1
prisma:query UPDATE "public"."User" SET "firstName" = $1, "lastName" = $2, "postcode" = $3, "email" = $4, "phoneNumber" = $5, "aboutMe" = $6, "updatedAt" = $7 WHERE ("public"."User"."id" = $8 AND 1=1) RETURNING "public"."User"."id", "public"."User"."name", "public"."User"."firstName", "public"."User"."lastName", "public"."User"."postcode", "public"."User"."avatar", "public"."User"."email", "public"."User"."phoneNumber", "public"."User"."aboutMe", "public"."User"."createdAt", "public"."User"."updatedAt"
Server: Successfully updated DB user record with ID: user_2zPQd2ZhtqDzxIU7NU2s45utyRs
Server: Clerk publicMetadata updated for user: user_2zPQd2ZhtqDzxIU7NU2s45utyRs
 PUT /api/onboarding 200 in 1074ms
 GET / 200 in 152ms
Answered by West African Lion
so now i will just store those updated fields in clerk metadata instead
View full answer

200 Replies

Dutch
Show your prisma query and logic to update user. And probably you need to use clerk to update user info
@Dutch Show your prisma query and logic to update user. And probably you need to use clerk to update user info
West African LionOP
const userRecord = await db.user.update({
    where: {
        id: userIdForDb,
    },
    data: {
        // Remove `id` from here if it was still there, and remove all `?.` from validatedData.data.field
        firstName: validatedData.data.firstName,
        lastName: validatedData.data.lastName,
        postcode: validatedData.data.postcode, // Make sure these fields are correctly passed from validatedData
        email: validatedData.data.email,
        phoneNumber: validatedData.data.phoneNumber,
        aboutMe: validatedData.data.aboutMe,
    },
});
for clerk, i just set a tag for the user which looks like this:
const updatedClerkUser = await (await clerkClient()).users.updateUser(user.id, {
     publicMetadata: {
         onboarded: true,
     },
});
Dutch
Check the null status of each variable you send like userId
@Dutch Check the null status of each variable you send like userId
West African LionOP
if i update from the nextjs app, it stays as NULL
@West African Lion if i update from the nextjs app, it stays as `NULL`
Dutch
find out why it s null
@Dutch find out why it s null
West African LionOP
thats why i'm here
i can't
all tests logs show as passed
Dutch
and add lines like
if (!userId) return error etc
@Dutch and add lines like `if (!userId) return error` etc
West African LionOP
yup and console.log data which is being sent to the db. thats when i get this:
Server: User ID from Clerk session (currentUser): user_2zPQd2ZhtqDzxIU7NU2s45utyRs
Server: User ID from form data (validatedData): {
  firstName: 'Lama',
  lastName: 'Baioi',
  postcode: 'BL1 3BH',
  email: 'mansoor.eb@gmail.com',
  phoneNumber: '0753791889',
  aboutMe: 'FIRST NAME LAST NAME'
}
Server: Attempting to update DB for ID: user_2zPQd2ZhtqDzxIU7NU2s45utyRs
prisma:query SELECT 1
prisma:query UPDATE "public"."User" SET "firstName" = $1, "lastName" = $2, "postcode" = $3, "email" = $4, "phoneNumber" = $5, "aboutMe" = $6, "updatedAt" = $7 WHERE ("public"."User"."id" = $8 AND 1=1) RETURNING "public"."User"."id", "public"."User"."name", "public"."User"."firstName", "public"."User"."lastName", "public"."User"."postcode", "public"."User"."avatar", "public"."User"."email", "public"."User"."phoneNumber", "public"."User"."aboutMe", "public"."User"."createdAt", "public"."User"."updatedAt"
Server: Successfully updated DB user record with ID: user_2zPQd2ZhtqDzxIU7NU2s45utyRs
Server: Clerk publicMetadata updated for user: user_2zPQd2ZhtqDzxIU7NU2s45utyRs
 PUT /api/onboarding 200 in 1074ms
 GET / 200 in 152ms
West African LionOP
try-catch on the API side
try-catch when sending json request:
    try {
      const response = await fetch("/api/onboarding", {
        method: "PUT",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(formData),
      });
      console.log('body:', formData);

      if (!response.ok) {
        const errorData = await response.json();
        console.error("API Error:", errorData.error);
        if (errorData.details) {
          const apiErrors: Partial<FormData> = {};
          errorData.details.forEach((detail: any) => {
            if (detail.path && detail.path[0]) {
              apiErrors[detail.path[0] as keyof FormData] = detail.message;
            }
          });
          setErrors(apiErrors);
        }
        throw new Error(errorData.error || "Failed to submit onboarding data");
      }

      setIsSubmitted(true);
    } catch (error) {
      console.error("Onboarding submission error:", error);
      setErrors({ email: "An unexpected error occurred. Please try again." });
    } finally {
      setIsSubmitting(false);
    }
  };
try-catch for the form to make sure all the values are as expected and aren't causing issues:
  const validateForm = (): boolean => {
    try {
      formDataSchema.parse(formData);
      setErrors({});
      return true;
    } catch (e) {
      if (e instanceof z.ZodError) {
        const newErrors: Partial<FormData> = {};
        for (const issue of e.issues) {
          if (issue.path[0]) {
            newErrors[issue.path[0] as keyof FormData] = issue.message;
          }
        }
        setErrors(newErrors);
      }
      return false;
    }
  };
Dutch
okay now,
do you see here at console totally correct
console.log('body:', formData);
totally correct, right ID, right values, right data format
Dutch
okay then its related with backend
West African LionOP
thats the whole API route
@Dutch okay then its related with backend
West African LionOP
i had the same idea but that is also returning the right values 😭
i asked couple of my friends and they couldn't see any issue
i asked in the neon server but no one replied
Dutch
i think its related with here
const userRecord = await db.user.update({
            where: {
                id: userIdForDb,
            },
            data: {
                // Remove `id` from here if it was still there, and remove all `?.` from validatedData.data.field
                firstName: validatedData.data.firstName,
                lastName: validatedData.data.lastName,
                postcode: validatedData.data.postcode, // Make sure these fields are correctly passed from validatedData
                email: validatedData.data.email,
                phoneNumber: validatedData.data.phoneNumber,
                aboutMe: validatedData.data.aboutMe,
            },
        });
        console.log("Server: Successfully updated DB user record with ID:", userRecord.id);
Dutch
where you see null
West African LionOP
postcode, phone number, and about me
cuz those things are not in the google oAuth
Dutch
i think you need to send id in data too
West African LionOP
so if you signin, it will take you to /onboarding, some of the fields will be missing which i want to update
@Dutch i think you need to send id in data too
West African LionOP
i did had it initial but it didn't work, gemini says that i have to keep it in where: and remove it from data: but again it doesn't work
also the reason for all those comments in the file
i can give you access to the repository if that helps in any way
Dutch
oh AI 😄
@Dutch oh AI 😄
West African LionOP
been stuck here for a month, broski couldn't help </3
Dutch
just try it like this
const userRecord = await db.user.update({
            data: {
                id: userIdForDb || validatedData.data.whatever
                firstName: validatedData.data.firstName,
                lastName: validatedData.data.lastName,
                postcode: validatedData.data.postcode, // Make sure these fields are correctly passed from validatedData
                email: validatedData.data.email,
                phoneNumber: validatedData.data.phoneNumber,
                aboutMe: validatedData.data.aboutMe,
            },
        });
        console.log("Updated user", userRecord);
AI made me lose more time than it should gain 😄
@Dutch AI made me lose more time than it should gain 😄
West African LionOP
genuinely
Dutch
maybe you need to rerun prisma studio somehow
there was migrate commands
West African LionOP
i have done that as well
nuke the db and generate tables with schema
rotated API keys too
Dutch
no no, it was like prisma update
btw, do you see some live logs at terminal when you run that commands
@Dutch no no, it was like prisma update
West African LionOP
i got these for now
"db:generate": "prisma migrate dev",
"db:migrate": "prisma migrate deploy",
"db:push": "prisma db push",
"db:studio": "prisma studio",
Dutch
yea migrate and push
@Dutch btw, do you see some live logs at terminal when you run that commands
West African LionOP
@West African Lion Click to see attachment
Dutch
no at prisma tab on terminal
hope you are running prisma while building app :lolsob:
with prisma studio?
wait but user creation and deletion works rn so not running prisma shouldn't be an issue no?
@Dutch how will you see updated user without studio
West African LionOP
neon dashboard
@West African Lion neon dashboard
Dutch
then remove prisma totally and call it a day ! 😄
@Dutch then remove prisma totally and call it a day ! 😄
West African LionOP
it's a Prisma DB on neon
I'm so confused here
@West African Lion I'm so confused here
Dutch
make it neon postgres and connect to it via raw sql
import { neon } from '@neondatabase/serverless';

export async function GET() {
    const sql = neon(process.env.DATABASE_URL);

    const rows = await sql("SELECT * FROM posts");

    return Response.json({ rows })
}
Dutch
okay then, show me that line with prisma:query at your code
West African LionOP
just let the local server run and it shows me this every now and then:
Dutch
looks like its closing connection before writing to db, thats why you dont see any updates on db
West African LionOP
but thats after those reuqests tho
not before
which seems normal
@Dutch okay then, show me that line with prisma:query at your code
West African LionOP
i don't have that
do you mean the prisma client?
Dutch
have you tried what i said cuz i am still seeing where clause at query
West African LionOP
i don't have "prisma:query" anywhere in my code
elaborate, what do you mean?
i'm new to this so bear with me please
Dutch
is your code same with it
const userRecord = await db.user.update({
data: {
id: userIdForDb || validatedData.data.whatever
firstName: validatedData.data.firstName,
lastName: validatedData.data.lastName,
postcode: validatedData.data.postcode, // Make sure these fields are correctly passed from validatedData
email: validatedData.data.email,
phoneNumber: validatedData.data.phoneNumber,
aboutMe: validatedData.data.aboutMe,
},
});
console.log("Updated user", userRecord);
Dutch
cuz it still has where clause
have you ran migrate push and studio commands
West African LionOP
yes
wait you might've cooked here
no nvm
still no db update after running those commands
Dutch
can you remove cache and run generate again
/Users/USER/.cache/prisma/studio/
/Users/__USER__/.cache/prisma/studio/
and as a suggestion, use drizzle or raw sql instead prisma
West African LionOP
i would but now i want to know what is stopping this mf to update
let me try cache
@West African Lion i would but now i want to know what is stopping this mf to update
Dutch
write that raw query to neon to see what is wrong
West African LionOP
alright so, i ran all these commands:
rm -rf prisma/migrations/
rm -rf .next
pnpm db:generate
pnpm db:push 


deleted the user from clerk, confirmed on the db (it was deleted). ran pnpm dev, created an account and did the /onboarding but no luck still.
Dutch
/Users/__USER__/.cache/prisma/studio/
West African LionOP
i'm on linux
Dutch
find that .cache folder
also dont forget to run migrate command
West African LionOP
1. deleted /cache/prisma
2. deleted .next
3. pnpm dev
4. go through everything
6. pnpm db:migrate
7. same log, same result
Dutch
okay instead prisma, run a raw query to neon and see what happens
West African LionOP
the userID is from the logs
Dutch
UPDATE "public"."User" SET "firstName" = "Some User", "lastName" = "Whatever", "postcode" = $3, "email" = $4, "phoneNumber" = $5, "aboutMe" = $6, "updatedAt" = $7 WHERE ("public"."User"."id" = "user_dgfdhfhfg" AND 1=1) RETURNING "public"."User"."id", "public"."User"."name", "public"."User"."firstName", "public"."User"."lastName", "public"."User"."postcode", "public"."User"."avatar", "public"."User"."email", "public"."User"."phoneNumber", "public"."User"."aboutMe", "public"."User"."createdAt", "public"."User"."updatedAt"
West African LionOP
i will have to change the $ tho
eitherway, trying now
Dutch
yea lol
West African LionOP
ran this:
UPDATE "public"."User"
SET
    "firstName" = 'Mansoor UPDATED',
    "lastName" = 'Barri UPDATED',
    "postcode" = 'MV12 9XH',
    "email" = 'mansoor.eb.ak@gmail.com',
    "phoneNumber" = '0750357919349',
    "aboutMe" = 'this is updated on neon'
WHERE
    "public"."User"."id" = 'user_2zWKT4tvKGWacjE12hZ1A5vPzAi'
RETURNING
    "public"."User"."id",
    "public"."User"."name",
    "public"."User"."firstName",
    "public"."User"."lastName",
    "public"."User"."postcode",
    "public"."User"."avatar",
    "public"."User"."email",
    "public"."User"."phoneNumber",
    "public"."User"."aboutMe",
    "public"."User"."createdAt",
    "public"."User"."updatedAt";
worked!
Dutch
nice, either you have a problem with prisma or your api
Dutch
from logs you dont have it with your api
West African LionOP
i literally installed prisma from pnpm
i have no idea what is wrong
Dutch
can you run same commands with npm
@West African Lion i literally installed prisma from pnpm
Prothonotary Warbler
Instead of prisma you could try mongoose
@Prothonotary Warbler Instead of prisma you could try mongoose
West African LionOP
thats my go-to thing but i wanna learn sql-based db
@Dutch can you run same commands with npm
West African LionOP
migrate and stuff?
Dutch
yes
and as a reminder, you cant go anywhere without knowing sql
@Dutch yes
West African LionOP
no luck
@Dutch and as a reminder, you cant go anywhere without knowing sql
Prothonotary Warbler
xD thats what I was thinking, this dude learned dynamic databases before sql
Dutch
i think you are cursed then
can you send me a live share link on vscode
@Prothonotary Warbler xD thats what I was thinking, this dude learned dynamic databases before sql
West African LionOP
you are getting me wrong, ik sql but not as much
its like how a backend developer would know frontend too but doesn't yk?
Dutch
bro a backend dev should know SQL 😄
West African LionOP
i'm new to BE
Dutch
sorry i kinda lost my sanity a bit
Prothonotary Warbler
lol
West African LionOP
this is literally my first fullstack app
@West African Lion this is literally my first fullstack app
Prothonotary Warbler
oh thats awesome man
Dutch
weird one is it s totally correct and working
can you show the logs of that command like
prisma generate
...
prisma migrate
...
etc
West African LionOP
let me send the live share link thing
Prothonotary Warbler
Just to be clear, the frontend doesnt show the fields from the db even tho you update it?
West African LionOP
@Prothonotary Warbler Just to be clear, the frontend doesnt show the fields from the db even tho you update it?
West African LionOP
the db doesn't update the fields when i update the db from the app. it works when i update using the sql editor on neon and with postman
@West African Lion the db doesn't update the fields when i update the db from the app. it works when i update using the sql editor on neon and with postman
Prothonotary Warbler
ohh this has happened to me before but using mongodb, its something abt how nextjs cache is stored atleast that was my case
bc there are different ways that you can call the fields from the database on next, thats for SEO improvements
West African LionOP
so the fix was to shift to mongo?
@West African Lion so the fix was to shift to mongo?
Prothonotary Warbler
not at all, its a Next issue
i was using mongo all the time
West African LionOP
what fixed it tho
Dutch
can you send another link pls
@West African Lion what fixed it tho
Prothonotary Warbler
instead of using getStaticProps that only fetched the data while it was building/compiling, to using getServerSideProps or api routes that dont rely on static generation thingys
Prothonotary Warbler
next only fetched an image of whats in the db, and when I tried to update it from the app it wouldnt show the changes
@West African Lion i'm not using `getStaticProps`
Prothonotary Warbler
which r u using?
West African LionOP
i'm not showing any changes in app for now
the flow rn is
- the user signups
- they get a form
- the form triggers a PUT functions to update the db.
the issue is that the PUT function doesn't reflect in the db
Prothonotary Warbler
are you by any chance missing an await?
@Prothonotary Warbler are you by any chance missing an `await`?
West African LionOP
nope
@Dutch let me run again
Prothonotary Warbler
well, last hope, console log the routes ur using...
West African LionOP
your changes will result in an error imo tho
Prothonotary Warbler
gl in ur 1st fullstack app!
West African LionOP
@Dutch
@Prothonotary Warbler gl in ur 1st fullstack app!
West African LionOP
thank you!
Dutch
nice, its working at least
West African LionOP
working?
well now the log showing an error too
the db still not updated
my wifi isn't wifi-ing
Dutch
yes it proves that your prisma is okay too
@Dutch yes it proves that your prisma is okay too
West African LionOP
oh makes sense
Dutch
my brain is not braining 😄
West African LionOP
i've had 4 sleepless nights over this
i have restarted this whole project too but still the same issue
Dutch
last resort is using pg adapter
West African LionOP
eitherway
i need to know why this isn't working
Dutch
says host offline
Dutch
still same
try that one
West African LionOP
@Dutch just confirmed again about the updatedAt
it does update that but nothing else
West African LionOP
@Dutch, i'm going afk for like 10-15 minutes
Dutch
okay
West African LionOP
Dutch
Hello i will be available in half hour, what about you @West African Lion
but update
i did make another API for POST and PUT and it works fine with all data being created and updated
💀
West African LionOP
so now i will just store those updated fields in clerk metadata instead
Answer
@West African Lion so now i will just store those updated fields in clerk metadata instead
Dutch
Really goos to hear ! Was thinking the non existent reasons 🙂
West African LionOP
but still dk why the that exact router doesn't work
i think my code is the issue but idkkkkkkkkkkkkkkk
Dutch
Put both side by side and see what you changed @West African Lion
West African LionOP
i have two theories: either its how my router checked for "success" or clerk
West African LionOP
got it working now finally sigh