🍪 Note: Our web-capstone-docs subdomain is a cookie-free zone.
Additional Libraries
Personalize Data

Personalize Data

To make sure every user get's their own data, we need a way to assign some data to a user. Here is the best way to do so: We add the property owner to the DB Model and save the user's id with every new dataset they create. To achieve this, we need to take the following steps:

💡

Take a look at the example implementation (opens in a new tab) on GitHub. Each step in this chapter is stored in a single commit.

Adapt the model

The idea is to add an 'owner' to every dataset. In order to achieve this we need to extend the schema of our DB model.

const placeSchema = new Schema({
  name: String,
  location: String,
  owner: { type: String, required: true }
});

Make use of the (server side) helperfunction getToken()

NextAuth provides a helper function getToken() which can only be used on the server. The token contains the original userId from the provider. We want to grab this userId and save it as an identifier with the data.

Good to know: This sensitive information is only used server side and will not be exposed to the client.

Inside the API route (e.g. /pages/api/places/index.js):

// ... 
import { getToken } from "next-auth/jwt";
 
export default async function handler(request, response){
  // ... 
  const token = await getToken({ req: request });
  const userId = token.sub;
  // ...
}

If you want to implement a user collection in your mongoDB you can use this userId as an identifier as well.

Adapt the POST request

Now we have to adapt the POST request: We are still using the create() method but we have to extend the data object with the 'owner' property.

if (session) {
  const placeData = request.body;
  await Place.create({ ...placeData, owner: userId });
  response.status(201).json({ status: "Place created" });
} else {
  response.status(401).json({ status: "Not authorized" });
}

Adapt the GET request

Since every dataset now has an 'owner' we can use this property to find specific data. We are still using the models find() method but now we pass an object as an argument find({ owner: userId }). This way we reduce the found datasets to those which match the given property.

if (session) {
  const places = await Place.find({ owner: userId });
  return response.status(200).json(places);
} else {
  const places = await Place.find({ owner: "default" });
  return response.status(200).json(places);
}

In this example the DB has some default data for users that are not logged in.