April 27, 2022

Build A Fullstack App with Remix, Prisma & MongoDB: CRUD, Filtering & Sorting

17 min read

Welcome to the third article of this series where you are learning how to build a full-stack application from the ground up using MongoDB, Prisma, and Remix! In this part, you will build out the main piece of the application which displays a user's kudos feed and allows them to send kudos to other users.

Build A Fullstack App with Remix, Prisma & MongoDB: CRUD, Filtering & Sorting

Table Of Contents


In the last part of this series you built your application's sign in and sign up forms and implemented session-based authentication. You also updated your Prisma schema to account for a new embedded document in the User model that will hold a user's profile data.

In this part you will build the main functionality of the application: the kudos feed. Each user will have a feed of kudos other users have sent them. Users will also be able to send other users kudos.

In addition, you will implement some searching and filtering to make it easier to find kudos in the feed.

The starting point for this project is available in the part-2 branch of the GitHub repository. If you'd like to see the final result of this part, head over to the part-3 branch.

Development environment

In order to follow along with the examples provided, you will be expected to ...

Note: The optional extensions add some really nice intellisense and syntax highlighting for Tailwind and Prisma.

Build a home route

The main section of your application will live in a /home route. Set up that route by adding a home.tsx file in the app/routes folder.

This new file should export a function component called Home for now, along with a loader function that redirects to the user to the login screen they are not logged in.

This /home route will act as the main page of your application rather than the base url.

Currently, the app/routes/index.tsx file (the / route) renders a React component. That route should only ever redirect a user: either to the /home or /login route. Set up a resource route in its place to achieve that functionality.

Resource routes

A resource route is a route that does not render a component, but can instead respond with any type of response. Think of it as a simple API endpoint. In your / route's case, you will want it to return a redirect response with a 302 status code.

Delete the existing app/routes/index.tsx file and replace it with an index.ts file where you will define the resource route:

Note: The file's extension was changed to .ts because this route will never render a component.

The loader above will first check if a user is logged in when they hit the / route. The requireUserId function will redirect to /login if there isn't a valid session.

If there is a valid session, the loader returns a redirect to the /home page.

Add the user list panel

Start off your home page by building a component that will list the site's users on the left side of the screen.

Create a new file in the app/components folder named user-panel.tsx:

This creates the side panel that will contain the list of users. The component is static though, meaning it does not perform any actions or vary in any way.

Before making this component more dynamic by adding a list of users, import it into the app/routes/home.tsx page and render it onto the page.

The code above imports the new component and the Layout component, then renders the new component within the layout.

Query for all users and sort the results

Now you need to actually show the list of users within the panel. You should already have a file where user-related functions will live: app/utils/user.server.ts.

Add a new function to that file that queries for any users in your database. This function should take in a userId parameter and sort the results by the user's first name in ascending order:

The where filter excludes any documents whose id matches the userId parameter. This will be used to grab every user except the currently logged in user.

Note: Notice how easy it is to sort by fields within an embedded document?

In app/routes/home.tsx, import that new function and invoke it within the loader. Then return the user list using Remix's json helper:

Note: Any code that is run within a loader function is not exposed to the client-side code. You can thank Remix for this awesome feature!

If you had any users in your database and outputted the users variable inside of the loader, you should see a list of all users except yourself.

Note: The entire profile embedded document was retrieved as a nested object without having to explicitly include it.

You will now have the data available. It's time to do something with it!

Provide the users to the user panel

Set up a new users prop in the UserPanel component.

The User type used here was generated by Prisma and is available via Prisma Client. Remix works very nicely with Prisma because it is extremely easy to achieve end-to-end type safety in a fullstack framework.

Note: End-to-end type safety occurs when the types across your entire stack are kept in sync as the shape of your data changes.

In app/routes/home.tsx you may now supply the users to the UserPanel component. Import the useLoaderData hook provided by Remix which gives you access to any data returned from the loader function and use it to access the users data:

The component will now have the users to work with. Now it needs to display them.

Build the user display component

The list items will be displayed as a circle with the first letter of the user's first and last names for now.

Create a new file in app/components named user-circle.tsx and add the following component to it:

This component uses the Profile type generated by Prisma because you will be passing in only the profile data from the user documents.

It also has some configurable options that allow you to provide a click action and add additional classes to customize its style.

In app/components/user-panel.tsx, import this new component and render one for each user instead of rendering <p>Users go here</p>:

Beautiful! Your users will now be rendered in a nice column on the left side of the home page. The only non-functional piece of the side panel at this point is the sign out button.

Add the ability to log out

Add another resource route in app/routes called logout.ts which will perform a logout action when invoked:

This route handles two possible actions: POST and GET

  • POST: This will trigger the logout function written in the previous part of this series.
  • GET: If a GET request is made, the user will be sent to the home page.

Add a form around your sign out button in app/components/user-panel.ts that will post to this route when submitted.

Your users can now sign out of the application! The user whose session is associated with the POST request will be signed out and their session destroyed.

Add the ability to send kudos

When a user in the user list is clicked a modal should pop up that provides a form. Submitting this form will save a kudo in the database.

This form will have the following features:

  • A display of which user you are giving kudos to.
  • A text area where you can fill out a message to the user.
  • Styling options that allow you to pick the post's background color and text color.
  • An emoji selector where you can add an emoji to the post.
  • An accurate preview of what your post will look like.

Update the Prisma schema

There are a couple of data points you will be saving and displaying that are not yet defined in your schema. Here's a list of what needs to change:

  1. Add a Kudo model with an embedded document to hold the style customizations
  2. Add a 1:n relation in the User model that defines the kudos a user is the author of. Also add a similar relation that defines the kudos a user is a recipient of.
  3. Add enums for emojis, departments, and colors to define the available options.

Note: After applying @default to a field, if a record in your collection does not have the new required field if will be updated to include that field with the default value the next time it is read.

That's all you'll need to update for now. Run npx prisma db push, which will automatically re-generate PrismaClient.

Nested routes

You will use a nested route to create the modal that will hold your form. This will allow you to set up a sub-route that will be rendered onto the parent route at an Outlet that you define.

When a user navigates to this nested route, a modal will be rendered onto the screen without having to re-render the entire page.

To create the nested route, first add a new folder in app/routes named home.

Note: The naming of that folder is important. Because you have a home.tsx file, Remix will recognize any files in the new home folder as sub-routes of /home.

Within the new app/routes/home directory, create a new file named kudo.$userId.tsx. This will allow you to handle the modal component as if it were its own route.

The $userId portion of this file name is a route param, which acts as a dynamic value you can provide your application via the URL. Remix will then translate that file name to the route: /home/kudos/$userId where $userId can be any value.

In that new file export a loader function and a React component that renders some text to make sure the dynamic value is working:

The code above does a few things:

  1. It pulls the params field from the loader function.
  2. It then grabs the userId value.
  3. Finally, it retrieves the data from the loader function using Remix's userLoaderData hook and renders the userId onto the screen.

Because this is a nested route, in order to display it you will need to define where the route should be outputted in its parent.

Use Remix's Outlet component to specify you want the child route to be rendered as a direct child of the Layout component in app/routes/home.tsx:

If you head over to http://localhost:3000/home/kudo/123, you should now see the text "User: 123" displayed at the very top of the page. If you change the value in the URL to something other than 123 you should see that change reflected on the screen.

Fetch a user by their id

Your nested route is working, but you still need to retrieve a user's data using the userId. Create a new function in app/utils/user.server.ts that returns a single user based on their id:

The query above finds the unique record in the database with the given id. The findUnique function allows you to filter your query using uniquely identifying fields, or fields with values that must be unique to that record within your database.


  1. Call that function in the loader exported by app/routes/home/kudo.$userId.tsx.
  2. Return the results from that loader using the json function.

Next, you need a way to navigate to a nested route with a valid id.

In app/components/user-panel.tsx, the file where you are rendering the user list, import the useNavigation hook Remix provides and use it to navigate to the nested route when a user is clicked.

Now when your users click on another user in that panel, they will be navigated to a sub-route with that user's information.

If that all looks good, the next step is building the modal component that will display your form.

Open a portal

To build this modal you will first need to build a helper component that creates a portal, which allows you to render a child component somewhere outside of the parent's document object model (DOM) branch while still allowing the parent component to manage it as if it were a direct child.

Note: This portal will be important because it will allow you to render the modal in a location that does not have any inherited styles or positioning from a parent that could affect the positioning of the modal.

In app/components create a new file named portal.tsx with the following contents:

Here's an explanation of what is going on in this component:

  1. A function is defined that generates a div with an id. That element is then attached to the document's body.
  2. If an element with the provided id does not already exist, invoke the createWrapper function to create one.
  3. When the Portal component is un-mounted, this will destroy the element.
  4. Creates a portal to the newly generated div.

The result will be that any element or component wrapped in this Portal will be rendered as a direct child of the body tag, rather than in the current DOM branch as a child of its parent.

Give this a try to see it in action. In app/routes/home/kudos.$userId.tsx, import the new Portal component and wrap the the returned component with it:

If you navigate to your nested route, you will see a div with an id of "kudo-modal" is now rendered as a direct child of the body rather than where the nested route is being rendered in the DOM tree.

Build the modal component

Now that you have a portal to a safe, begin building the modal component itself. There will be two modals in this application, so build the component in a way that is reusable.

Create a new file at app/components/modal.tsx. This file should export a component with the following props:

  • children: The elements to render within the modal.
  • isOpen: A flag that determines whether or not the modal is being displayed.
  • ariaLabel: (optional) A string to be used as an aria label.
  • className: (optional) A string that allows you to add additional classes to the modal's contents.

Add the following code to create the Modal component:

The Portal component is imported and wraps the entirety of the modal to ensure it is rendered in a safe location.

The modal is then defined as a fixed element on the screen with an opaque backdrop using various TailwindCSS helpers.

When the backdrop (anywhere off of the modal itself) is clicked, the user will be navigated to the /home route causing the modal to close.

Build the form

In app/routes/home/kudo.$userId.tsx import the new Modal component and render a Modal instead of the Portal currently being rendered:

The modal should now open up when a user from the side panel is clicked.

Your form will need the logged in user's information when it displays a preview of the message, so before building the form add that data to the response from the loader function:

Then make the following changes to the KudoModal function in that file:

This was a big chunk of new code, so take a look at what changes were made:

  1. Imports a few components and hooks you will need.
  2. Sets up the various form variables you will need to handle the form data and errors.
  3. Creates the function that will handle input changes.
  4. Renders the basic layout of the form component in place of what was the <h2> tag.

Allow the user to customize their kudo

This form also needs to allow the user to select custom styles using select boxes.

Create a new file in app/components named select-box.tsx that exports a SelectBox component:

This component is similar to the FormField component in that it is a controlled component that takes in some configuration and allows its state to be managed by its parent.

These select boxes will need to be populated with the color and emoji options. Create a helper file to hold the possible options at app/utils/constants.ts:

Now in app/routes/home/kudo.$userId.tsx, import the SelectBox component and the constants. Also add the variables and functions requried to hook them up to the form's state and render the SelectBox components in place of the {/* Select Boxes Go Here */} comment:

The select boxes will now appear with all of the possible options.

Add a kudo display component

This form will have a preview section where the user can see an actual rendering of the component the recipient will see.

Create a new file at app/components named kudo.tsx:

This component takes in the props:

  • profile: The profile data from the recipients user document.
  • kudo: The Kudo's data and styling options.

The constants with color and emoji options are imported and used to render the customized styles.

You can now import this component into app/routes/home/kudo.$userId.tsx and render it in place of the {/* The Preview Goes Here */} comment:

The preview will now be rendered, displaying the currently logged in user's information and the styled message they are going to send.

Build the action to send kudos

The form is now visually complete and the only piece that remains is making it functional!

Create a new file in app/utils named kudos.server.ts where you will write any functions related to querying or storing kudos.

In this file, export a createKudo method that takes in the kudo form data, the author's id and the recipient's id. Then store that data using Prisma:

The query above does the following:

  1. Passes in the message string and style embedded document.
  2. Connects the new kudo to the appropriate author and recipient using the ids passed to the function.

Import this new function into the app/routes/home/kudo.$userId.tsx file and create an action function to handle the form data and the invocation of the createKudo function:

Here's an overview of the snippet above:

  1. Imports the new createKudo function, along with a few types generated by Prisma, the ActionFunction type from Remix, and the requireUserId function you wrote previously.
  2. Pulls out all of the form data and fields you need from the request.
  3. Validates all of the form data and send the appropriate errors back to the form to be displayed if something goes wrong.
  4. Creates the new kudo using the createKudo function.
  5. Redirects the user to the /home route, causing the modal to close.

Build a kudos feed

Now that your users can send kudos to each other, you will need a way to display those kudos in the user's feed on the /home page.

You already built the kudo display component, so you simply need to retrieve and render out a list of kudos on the home page.

In app/utils/kudos.server.ts create and export a new function named getFilteredKudos.

The function above takes in a few different parameters. Here is what those are:

  • userId: The id of the user whose kudos the query should retrieve.
  • sortFilter: An object that will be passed into the orderBy option in the query to sort the results.
  • whereFilter: An object that will be passed into the where option in the query to filter the results.

Note: Prisma generates types that can be used to safely type pieces of your queries, such as the Prisma.KudoWhereInput used above.

Now in app/routes/home.tsx, import that function and invoke it in the loader function. Also import the Kudo component and the types required to render out the feed of Kudos.

The Kudo and Profile types generated by Prisma are combined to create a KudoWithProfile type. This is needed because your array has kudos that include the profile data from the author.

If you send a couple of kudos to an account and log in to that account, you should now see a rendered list of kudos on your feed.

You may notice when getFilteredKudos invocation is providing empty objects for the sort and filter options. This is because there is not yet a way in the UI to filter or sort the feed. Next, you will create the search bar at the top of the feed to handle this.

Create a new file in app/components named search-bar.tsx. This component will submit a form to the /home page, passing along query parameters that will be used to build up the sort and filter objects you need.

In the code above, an input and button were added to handle the text filter and submission of the search parameters.

When there is a filter variable present in the URL, the button will change to a "Clear Filters" button rather than the "Search" button.

Import that file into app/routes/home.tsx and render it in place of the {/* Search Bar Goes Here */} comment.

These changes will handle filtering the feed, however you also want to sort the feed by various columns.

In app/utils/constants.ts add a sortOptions constant that defines the columns available.

Now import that constant and the SelectBox component into the app/components/search-bar.tsx file and render the SelectBox with those options right before the button element.

Now you should see a dropdown available in the search bar with your options.

Build the search bar action

When the search form is submitted, a GET request will be made to /home with the filter and sort data passed along in the URL. In the loader function exported by app/routes/home.tsx, pull the sort and filter data from the URL and build a query with the results:

The code above:

  1. Pulls out the URL parameters.
  2. Builds a sortOptions object to pass into your Prisma query that may vary depending on the data passed in the URL.
  3. Builds a textFilter object to pass into your Prisma query that may vary depending on the data passed in the URL.
  4. Updates the getFilteredKudos invocation to include the new filters.

Now if you submit form you should see your results reflected on the feed!

Display the most recent kudos

The last thing your feed needs is a way to display the most recently sent kudos. This component will display a UserCircle component for the three most recent recipients of kudos.

Create a new file in app/components named recent-bar.tsx with the following code:

This component takes in a list of the top three recent kudos and renders them out into a panel.

Now you need to write a query that grabs that data. In app/utils/kudos.server.ts add a function named getRecentKudos that returns the following query:

This query:

  1. Sorts the results by createdAt in descending order to get the records from newest to oldest.
  2. Takes only the first three from that list to get the three most recent documents.

Now you will need to:

  • Import the RecentBar component and getRecentKudos function into the app/routes/home.tsx file.
  • Call getRecentKudos within that file's loader function.
  • Render the RecentBar onto the home page in place of the {/* Recent Kudos Goes Here */} comment.

With that, your home page is complete and you should see a list of the three most recent kudos sent in your application!

Summary & What's next

In this article you built the main pieces of functionality for this application, and learned a bunch of concepts along the way including:

  • Redirecting in Remix
  • Using resource routes
  • Filtering & sorting data with Prisma Client
  • Using embedded documents in your Prisma Schema
  • ... and lots more!

In the next section of this series, you will finish off this application by building out the profile settings section of the site and creating an image upload component to manage profile pictures.

Don’t miss the next post!

Sign up for the Prisma Newsletter