Next.js Discord

Discord Forum

clerk code explanation needed

Answered
rkstlohchab posted this in #help-forum
Open in Discord
i want to ask exactly what

if(newUser) {
      await clerkClient.users.updateUserMetadata(id, {
        publicMetadata: {
          userId: newUser._id
        }
      })
    }


is the use of above code inside the below code , why are we using it because we created user by clerkid by passing it to server action then why is this IF STATEMENT needed and what happens when i dont use it

why it isnt used in updated user webhook and only create user webhook



if(eventType === 'user.created') {
    const { id, email_addresses, image_url, first_name, last_name, username } = evt.data;

    const user = {
      clerkId: id,
      email: email_addresses[0].email_address,
      username: username!,
      firstName: first_name,
      lastName: last_name,
      photo: image_url,
    }

    const newUser = await createUser(user);

    if(newUser) {
      await clerkClient.users.updateUserMetadata(id, {
        publicMetadata: {
          userId: newUser._id
        }
      })
    }

    return NextResponse.json({ message: 'OK', user: newUser })
  }

  if (eventType === 'user.updated') {
    const {id, image_url, first_name, last_name, username } = evt.data

    const user = {
      firstName: first_name,
      lastName: last_name,
      username: username!,
      photo: image_url,
    }

    const updatedUser = await updateUser(id, user)

    return NextResponse.json({ message: 'OK', user: updatedUser })
  }


@"use php"
Answered by Clown
It should. I dont remember if the user id is available on the user object itself, but if it isnt then you definitely should still use this bit of code as the user id can be useful in many cases
View full answer

20 Replies

with
this
    const newUser = await createUser(user);
what is this doing
if(newUser) {
      await clerkClient.users.updateUserMetadata(id, {
        publicMetadata: {
          userId: newUser._id
        }
      })
    }
I don't think I can help you with this as I don't use clerk
oh wait
Its basically checking if a user is successfully created
if its successfully created, then it updates metadata
@rkstlohchab js if(newUser) { await clerkClient.users.updateUserMetadata(id, { publicMetadata: { userId: newUser._id } }) }
You can store a bit of metadata with your user that you want publicly available, you can add other stuff here aswell like user role, preferred color or something
and exactly what is metadata here?
@Clown Then, when you fetch your user you can use this metadata wherever you need
so basically if i dont use this the code will still work ?
It should. I dont remember if the user id is available on the user object itself, but if it isnt then you definitely should still use this bit of code as the user id can be useful in many cases
Answer
I think the guide explains this very well:
https://clerk.com/docs/users/metadata
thank you bro