Quickstart

We’re going to be short on words and quick on code in this quickstart. If you’re looking to see what Remix is all about in 15 minutes, this is it.

Work through this tutorial with Kent in this free Egghead.io course

This tutorial uses TypeScript. Remix can definitely be used without TypeScript. We feel most productive when writing TypeScript, but if you’d prefer to skip the TypeScript syntax, feel free to write your code in JavaScript.

💿 Hey I’m Derrick the Remix Compact Disc 👋 Whenever you’re supposed to do something you’ll see me

Prerequisites

Click this button to create a Gitpod workspace with the project set up and ready to run in VS Code or JetBrains either directly in the browser or on the desktop.

Gitpod Ready-to-Code

If you want to follow this tutorial locally on your own computer, it is important for you to have these things installed:

  • Node.js version (^14.17.0, or >=16.0.0)
  • npm 7 or greater
  • A code editor (VSCode is a nice one)

Creating the project

Make sure you are running at least Node v14 or greater

💿 Initialize a new Remix project. We’ll call ours “blog-tutorial” but you can call it something else if you’d like.

  1. npx create-remix@latest --template remix-run/indie-stack blog-tutorial
  1. ? Do you want me to run `npm install`? Yes

You can read more about the stacks available in the stacks docs.

We’re using the Indie stack, which is a full application ready to deploy to fly.io. This includes development tools as well as production-ready authentication and persistence. Don’t worry if you’re unfamiliar with the tools used, we’ll walk you through things as we go.

Note, you can definitely start with “Just the basics” instead by running npx create-remix@latest without the --template flag. The generated project is much more minimal that way. However, some bits of the tutorial will be different for you and you’ll have to configure things for deployment manually.

💿 Now, open the project that was generated in your preferred editor and check the instructions in the README.md file. Feel free to read over this. We’ll get to the deployment bit later in the tutorial.

💿 Let’s start the dev server:

  1. npm run dev

💿 Open up http://localhost:3000, the app should be running.

If you want, take a minute and poke around the UI a bit. Feel free to create an account and create/delete some notes to get an idea of what’s available in the UI out of the box.

Your First Route

We’re going to make a new route to render at the “/posts” URL. Before we do that, let’s link to it.

💿 Add a link to posts in app/routes/_index.tsx

Go ahead and copy/paste this:

  1. <div className="mx-auto mt-16 max-w-7xl text-center">
  2. <Link
  3. to="/posts"
  4. className="text-xl text-blue-600 underline"
  5. >
  6. Blog Posts
  7. </Link>
  8. </div>

You can put it anywhere you like. I stuck it right above the icons of all the technologies used in the stack:

Screenshot of the app showing the blog post link

You may have noticed we’re using Tailwind CSS classes.

The Remix Indie stack has Tailwind CSS support pre-configured. If you’d prefer to not use Tailwind CSS, you’re welcome to remove it and use something else. Learn more about your styling options with Remix in the styling guide.

Back in the browser go ahead and click the link. You should see a 404 page since we’ve not created this route yet. Let’s create the route now:

💿 Create a new file at app/routes/posts._index.tsx

  1. touch app/routes/posts._index.tsx

Any time you see terminal commands to create files or folders, you can of course do that however you’d like, but using touch is just a way for us to make it clear which files you should be creating.

We could have named it just posts.tsx but we’ll have another route soon, and it’ll be nice to put them by each other. An index route will render at the parent’s path (just like index.html on a web server).

Now if you navigate to the /posts route, you’ll get an error indicating there’s no way to handle the request. That’s because we haven’t done anything in that route yet! Let’s add a component and export it as the default:

💿 Make the posts component

  1. export default function Posts() {
  2. return (
  3. <main>
  4. <h1>Posts</h1>
  5. </main>
  6. );
  7. }

You might need to refresh the browser to see our new, bare-bones posts route.

Loading Data

Data loading is built into Remix.

If your web dev background is primarily in the last few years, you’re probably used to creating two things here: an API route to provide data and a frontend component that consumes it. In Remix your frontend component is also its own API route, and it already knows how to talk to itself on the server from the browser. That is, you don’t have to fetch it.

If your background is a bit farther back than that with MVC web frameworks like Rails, then you can think of your Remix routes as backend views using React for templating, but then they know how to seamlessly hydrate in the browser to add some flair instead of writing detached jQuery code to dress up the user interactions. It’s progressive enhancement realized in its fullest. Additionally, your routes are their own controller.

So let’s get to it and provide some data to our component.

💿 Make the posts route loader

  1. import { json } from "@remix-run/node";
  2. import { useLoaderData } from "@remix-run/react";
  3. export const loader = async () => {
  4. return json({
  5. posts: [
  6. {
  7. slug: "my-first-post",
  8. title: "My First Post",
  9. },
  10. {
  11. slug: "90s-mixtape",
  12. title: "A Mixtape I Made Just For You",
  13. },
  14. ],
  15. });
  16. };
  17. export default function Posts() {
  18. const { posts } = useLoaderData<typeof loader>();
  19. return (
  20. <main>
  21. <h1>Posts</h1>
  22. </main>
  23. );
  24. }

loader functions are the backend “API” for their component, and it’s already wired up for you through useLoaderData. It’s a little wild how blurry the line is between the client and the server in a Remix route. If you have your server and browser consoles both open, you’ll note that they both logged our post data. That’s because Remix rendered on the server to send a full HTML document like a traditional web framework, but it also hydrated in the client and logged there too.

Whatever you return from your loader will be exposed to the client, even if the component doesn’t render it. Treat your loaders with the same care as public API endpoints.

💿 Render links to our posts

  1. import { json } from "@remix-run/node";
  2. import { Link, useLoaderData } from "@remix-run/react";
  3. // ...
  4. export default function Posts() {
  5. const { posts } = useLoaderData<typeof loader>();
  6. return (
  7. <main>
  8. <h1>Posts</h1>
  9. <ul>
  10. {posts.map((post) => (
  11. <li key={post.slug}>
  12. <Link
  13. to={post.slug}
  14. className="text-blue-600 underline"
  15. >
  16. {post.title}
  17. </Link>
  18. </li>
  19. ))}
  20. </ul>
  21. </main>
  22. );
  23. }

Hey, that’s pretty cool. We get a pretty solid degree of type safety even over a network request because it’s all defined in the same file. Unless the network blows up while Remix fetches the data, you’ve got type safety in this component and its API (remember, the component is already its own API route).

A little refactoring

A solid practice is to create a module that deals with a particular concern. In our case it’s going to be reading and writing posts. Let’s set that up now and add a getPosts export to our module.

💿 Create app/models/post.server.ts

  1. touch app/models/post.server.ts

We’re mostly going to copy/paste stuff from our route:

  1. type Post = {
  2. slug: string;
  3. title: string;
  4. };
  5. export async function getPosts(): Promise<Array<Post>> {
  6. return [
  7. {
  8. slug: "my-first-post",
  9. title: "My First Post",
  10. },
  11. {
  12. slug: "90s-mixtape",
  13. title: "A Mixtape I Made Just For You",
  14. },
  15. ];
  16. }

Note that we’re making the getPosts function async because even though it’s not currently doing anything async it will soon!

💿 Update the posts route to use our new posts module:

  1. import { json } from "@remix-run/node";
  2. import { Link, useLoaderData } from "@remix-run/react";
  3. import { getPosts } from "~/models/post.server";
  4. export const loader = async () => {
  5. return json({ posts: await getPosts() });
  6. };
  7. // ...

Pulling from a data source

With the Indie Stack, we’ve got a SQLite database already set up and configured for us, so let’s update our Database Schema to handle SQLite. We’re using Prisma to interact with the database, so we’ll update that schema and Prisma will take care of updating our database to match the schema for us (as well as generating and running the necessary SQL commands for the migration).

You do not have to use Prisma when using Remix. Remix works great with whatever existing database or data persistence services you’re currently using.

If you’ve never used Prisma before, don’t worry, we’ll walk you through it.

💿 First, we need to update our Prisma schema:

  1. // Stick this at the bottom of that file:
  2. model Post {
  3. slug String @id
  4. title String
  5. markdown String
  6. createdAt DateTime @default(now())
  7. updatedAt DateTime @updatedAt
  8. }

💿 Let’s generate a migration file for our schema changes, which will be required if you deploy your application rather than just running in dev mode locally. This will also update our local database and TypeScript definitions to match the schema change. We’ll name the migration “create post model”.

  1. npx prisma migrate dev --name "create post model"

💿 Let’s seed our database with a couple posts. Open prisma/seed.ts and add this to the end of the seed functionality (right before the console.log):

  1. const posts = [
  2. {
  3. slug: "my-first-post",
  4. title: "My First Post",
  5. markdown: `
  6. # This is my first post
  7. Isn't it great?
  8. `.trim(),
  9. },
  10. {
  11. slug: "90s-mixtape",
  12. title: "A Mixtape I Made Just For You",
  13. markdown: `
  14. # 90s Mixtape
  15. - I wish (Skee-Lo)
  16. - This Is How We Do It (Montell Jordan)
  17. - Everlong (Foo Fighters)
  18. - Ms. Jackson (Outkast)
  19. - Interstate Love Song (Stone Temple Pilots)
  20. - Killing Me Softly With His Song (Fugees, Ms. Lauryn Hill)
  21. - Just a Friend (Biz Markie)
  22. - The Man Who Sold The World (Nirvana)
  23. - Semi-Charmed Life (Third Eye Blind)
  24. - ...Baby One More Time (Britney Spears)
  25. - Better Man (Pearl Jam)
  26. - It's All Coming Back to Me Now (Céline Dion)
  27. - This Kiss (Faith Hill)
  28. - Fly Away (Lenny Kravits)
  29. - Scar Tissue (Red Hot Chili Peppers)
  30. - Santa Monica (Everclear)
  31. - C'mon N' Ride it (Quad City DJ's)
  32. `.trim(),
  33. },
  34. ];
  35. for (const post of posts) {
  36. await prisma.post.upsert({
  37. where: { slug: post.slug },
  38. update: post,
  39. create: post,
  40. });
  41. }

Note that we’re using upsert so you can run the seed script over and over without adding multiple versions of the same post every time.

Great, let’s get those posts into the database with the seed script:

  1. npx prisma db seed

💿 Now update the app/models/post.server.ts file to read from the SQLite database:

  1. import { prisma } from "~/db.server";
  2. export async function getPosts() {
  3. return prisma.post.findMany();
  4. }

Notice we’re able to remove the return type, but everything is still fully typed. The TypeScript feature of Prisma is one of its greatest strengths. Less manual typing, but still type safe!

The ~/db.server import is importing the file at app/db.server.ts. The ~ is a fancy alias to the app directory, so you don’t have to worry about how many ../../s to include in your import as you move files around.

💿 Now that the Prisma client has been updated, we will need to restart our server. So stop the dev server and start it back up again with npm run dev.

You only need to ever do this when you change the Prisma schema and update the Prisma client. Normally you don’t need to restart the dev server during development. Nice that it’s so fast though right?

With the server up and running again, you should be able to go to http://localhost:3000/posts and the posts should still be there, but now they’re coming from SQLite!

Dynamic Route Params

Now let’s make a route to actually view the post. We want these URLs to work:

  1. /posts/my-first-post
  2. /posts/90s-mixtape

Instead of creating a route for every single one of our posts, we can use a “dynamic segment” in the url. Remix will parse and pass to us, so we can look up the post dynamically.

💿 Create a dynamic route at app/routes/posts.$slug.tsx

  1. touch app/routes/posts.$slug.tsx
  1. export default function PostSlug() {
  2. return (
  3. <main className="mx-auto max-w-4xl">
  4. <h1 className="my-6 border-b-2 text-center text-3xl">
  5. Some Post
  6. </h1>
  7. </main>
  8. );
  9. }

You can click one of your posts and should see the new page.

💿 Add a loader to access the params

  1. import type { LoaderArgs } from "@remix-run/node";
  2. import { json } from "@remix-run/node";
  3. import { useLoaderData } from "@remix-run/react";
  4. export const loader = async ({ params }: LoaderArgs) => {
  5. return json({ slug: params.slug });
  6. };
  7. export default function PostSlug() {
  8. const { slug } = useLoaderData<typeof loader>();
  9. return (
  10. <main className="mx-auto max-w-4xl">
  11. <h1 className="my-6 border-b-2 text-center text-3xl">
  12. Some Post: {slug}
  13. </h1>
  14. </main>
  15. );
  16. }

The part of the filename attached to the $ becomes a named key on the params object that comes into your loader. This is how we’ll look up our blog post.

Now, let’s actually get the post contents from the database by its slug.

💿 Add a getPost function to our post module

  1. import { prisma } from "~/db.server";
  2. export async function getPosts() {
  3. return prisma.post.findMany();
  4. }
  5. export async function getPost(slug: string) {
  6. return prisma.post.findUnique({ where: { slug } });
  7. }

💿 Use the new getPost function in the route

  1. import type { LoaderArgs } from "@remix-run/node";
  2. import { json } from "@remix-run/node";
  3. import { useLoaderData } from "@remix-run/react";
  4. import { getPost } from "~/models/post.server";
  5. export const loader = async ({ params }: LoaderArgs) => {
  6. const post = await getPost(params.slug);
  7. return json({ post });
  8. };
  9. export default function PostSlug() {
  10. const { post } = useLoaderData<typeof loader>();
  11. return (
  12. <main className="mx-auto max-w-4xl">
  13. <h1 className="my-6 border-b-2 text-center text-3xl">
  14. {post.title}
  15. </h1>
  16. </main>
  17. );
  18. }

Check that out! We’re now pulling our posts from a data source instead of including it all in the browser as JavaScript.

Let’s make TypeScript happy with our code:

  1. import type { LoaderArgs } from "@remix-run/node";
  2. import { json } from "@remix-run/node";
  3. import { useLoaderData } from "@remix-run/react";
  4. import invariant from "tiny-invariant";
  5. import { getPost } from "~/models/post.server";
  6. export const loader = async ({ params }: LoaderArgs) => {
  7. invariant(params.slug, "params.slug is required");
  8. const post = await getPost(params.slug);
  9. invariant(post, `Post not found: ${params.slug}`);
  10. return json({ post });
  11. };
  12. export default function PostSlug() {
  13. const { post } = useLoaderData<typeof loader>();
  14. return (
  15. <main className="mx-auto max-w-4xl">
  16. <h1 className="my-6 border-b-2 text-center text-3xl">
  17. {post.title}
  18. </h1>
  19. </main>
  20. );
  21. }

Quick note on that invariant for the params. Because params comes from the URL, we can’t be totally sure that params.slug will be defined—maybe you change the name of the file to posts.$postId.ts! It’s a good practice to validate that stuff with invariant, and it makes TypeScript happy too.

We also have an invariant for the post. We’ll handle the 404 case better later. Keep going!

Now let’s get that markdown parsed and rendered to HTML to the page. There are a lot of Markdown parsers, we’ll use marked for this tutorial because it’s really easy to get working.

💿 Parse the markdown into HTML

  1. npm add marked
  2. # additionally, if using typescript
  3. npm add @types/marked -D

Now that marked has been installed, we will need to restart our server. So stop the dev server and start it back up again with npm run dev.

  1. import type { LoaderArgs } from "@remix-run/node";
  2. import { json } from "@remix-run/node";
  3. import { useLoaderData } from "@remix-run/react";
  4. import { marked } from "marked";
  5. import invariant from "tiny-invariant";
  6. import { getPost } from "~/models/post.server";
  7. export const loader = async ({ params }: LoaderArgs) => {
  8. invariant(params.slug, "params.slug is required");
  9. const post = await getPost(params.slug);
  10. invariant(post, `Post not found: ${params.slug}`);
  11. const html = marked(post.markdown);
  12. return json({ html, post });
  13. };
  14. export default function PostSlug() {
  15. const { html, post } = useLoaderData<typeof loader>();
  16. return (
  17. <main className="mx-auto max-w-4xl">
  18. <h1 className="my-6 border-b-2 text-center text-3xl">
  19. {post.title}
  20. </h1>
  21. <div dangerouslySetInnerHTML={{ __html: html }} />
  22. </main>
  23. );
  24. }

Holy smokes, you did it. You have a blog. Check it out! Next, we’re going to make it easier to create new blog posts 📝

Nested Routing

Right now, our blog posts just come from seeding the database. Not a real solution, so we need a way to create a new blog post in the database. We’re going to be using actions for that.

Let’s make a new “admin” section of the app.

💿 First, let’s add a link to the admin section on the posts index route:

  1. // ...
  2. <Link to="admin" className="text-red-600 underline">
  3. Admin
  4. </Link>
  5. // ...

Put that anywhere in the component. I stuck it right under the <h1>.

Did you notice that the to prop is just “admin” and it linked to /posts/admin? With Remix, you get relative links.

💿 Create an admin route at app/routes/posts.admin.tsx:

  1. touch app/routes/posts.admin.tsx
  1. import { json } from "@remix-run/node";
  2. import { Link, useLoaderData } from "@remix-run/react";
  3. import { getPosts } from "~/models/post.server";
  4. export const loader = async () => {
  5. return json({ posts: await getPosts() });
  6. };
  7. export default function PostAdmin() {
  8. const { posts } = useLoaderData<typeof loader>();
  9. return (
  10. <div className="mx-auto max-w-4xl">
  11. <h1 className="my-6 mb-2 border-b-2 text-center text-3xl">
  12. Blog Admin
  13. </h1>
  14. <div className="grid grid-cols-4 gap-6">
  15. <nav className="col-span-4 md:col-span-1">
  16. <ul>
  17. {posts.map((post) => (
  18. <li key={post.slug}>
  19. <Link
  20. to={post.slug}
  21. className="text-blue-600 underline"
  22. >
  23. {post.title}
  24. </Link>
  25. </li>
  26. ))}
  27. </ul>
  28. </nav>
  29. <main className="col-span-4 md:col-span-3">
  30. ...
  31. </main>
  32. </div>
  33. </div>
  34. );
  35. }

You should recognize several of the things we’re doing in there from what we’ve done so far. With that, you should have a decent looking page with the posts on the left and a placeholder on the right. Now, if you click on the Admin link, it’ll take you to http://localhost:3000/posts/admin.

Index Routes

Let’s fill in that placeholder with an index route for admin. Hang with us, we’re introducing “nested routes” here where your route file nesting becomes UI component nesting.

💿 Create an index route for posts.admin.tsx‘s child routes

  1. touch app/routes/posts.admin._index.tsx
  1. import { Link } from "@remix-run/react";
  2. export default function AdminIndex() {
  3. return (
  4. <p>
  5. <Link to="new" className="text-blue-600 underline">
  6. Create a New Post
  7. </Link>
  8. </p>
  9. );
  10. }

If you refresh you’re not going to see it yet. Every route that starts with app/routes/posts.admin. can now render inside of app/routes/posts.admin.tsx when their URL matches. You get to control which part of the posts.admin.tsx layout the child routes render.

💿 Add an outlet to the admin page

  1. import { json } from "@remix-run/node";
  2. import {
  3. Link,
  4. Outlet,
  5. useLoaderData,
  6. } from "@remix-run/react";
  7. import { getPosts } from "~/models/post.server";
  8. export const loader = async () => {
  9. return json({ posts: await getPosts() });
  10. };
  11. export default function PostAdmin() {
  12. const { posts } = useLoaderData<typeof loader>();
  13. return (
  14. <div className="mx-auto max-w-4xl">
  15. <h1 className="my-6 mb-2 border-b-2 text-center text-3xl">
  16. Blog Admin
  17. </h1>
  18. <div className="grid grid-cols-4 gap-6">
  19. <nav className="col-span-4 md:col-span-1">
  20. <ul>
  21. {posts.map((post) => (
  22. <li key={post.slug}>
  23. <Link
  24. to={post.slug}
  25. className="text-blue-600 underline"
  26. >
  27. {post.title}
  28. </Link>
  29. </li>
  30. ))}
  31. </ul>
  32. </nav>
  33. <main className="col-span-4 md:col-span-3">
  34. <Outlet />
  35. </main>
  36. </div>
  37. </div>
  38. );
  39. }

Hang with us for a minute, index routes can be confusing at first. Just know that when the URL matches the parent route’s path, the index will render inside the Outlet.

Maybe this will help, let’s add the /posts/admin/new route and see what happens when we click the link.

💿 Create the app/routes/posts.admin.new.tsx file

  1. touch app/routes/posts.admin.new.tsx
  1. export default function NewPost() {
  2. return <h2>New Post</h2>;
  3. }

Now click the link from the index route and watch the <Outlet/> automatically swap out the index route for the “new” route!

Actions

We’re going to get serious now. Let’s build a form to create a new post in our new “new” route.

💿 Add a form to the new route

  1. import { Form } from "@remix-run/react";
  2. const inputClassName =
  3. "w-full rounded border border-gray-500 px-2 py-1 text-lg";
  4. export default function NewPost() {
  5. return (
  6. <Form method="post">
  7. <p>
  8. <label>
  9. Post Title:{" "}
  10. <input
  11. type="text"
  12. name="title"
  13. className={inputClassName}
  14. />
  15. </label>
  16. </p>
  17. <p>
  18. <label>
  19. Post Slug:{" "}
  20. <input
  21. type="text"
  22. name="slug"
  23. className={inputClassName}
  24. />
  25. </label>
  26. </p>
  27. <p>
  28. <label htmlFor="markdown">Markdown: </label>
  29. <br />
  30. <textarea
  31. id="markdown"
  32. rows={20}
  33. name="markdown"
  34. className={`${inputClassName} font-mono`}
  35. />
  36. </p>
  37. <p className="text-right">
  38. <button
  39. type="submit"
  40. className="rounded bg-blue-500 py-2 px-4 text-white hover:bg-blue-600 focus:bg-blue-400 disabled:bg-blue-300"
  41. >
  42. Create Post
  43. </button>
  44. </p>
  45. </Form>
  46. );
  47. }

If you love HTML like us, you should be getting pretty excited. If you’ve been doing a lot of <form onSubmit> and <button onClick> you’re about to have your mind blown by HTML.

All you really need for a feature like this is a form to get data from the user and a backend action to handle it. And in Remix, that’s all you have to do too.

Let’s create the essential code that knows how to save a post first in our post.ts module.

💿 Add createPost anywhere inside of app/models/post.server.ts

  1. // ...
  2. export async function createPost(post) {
  3. return prisma.post.create({ data: post });
  4. }

💿 Call createPost from the new post route’s action

  1. import type { ActionArgs } from "@remix-run/node";
  2. import { redirect } from "@remix-run/node";
  3. import { Form } from "@remix-run/react";
  4. import { createPost } from "~/models/post.server";
  5. export const action = async ({ request }: ActionArgs) => {
  6. const formData = await request.formData();
  7. const title = formData.get("title");
  8. const slug = formData.get("slug");
  9. const markdown = formData.get("markdown");
  10. await createPost({ title, slug, markdown });
  11. return redirect("/posts/admin");
  12. };
  13. // ...

That’s it. Remix (and the browser) will take care of the rest. Click the submit button and watch the sidebar that lists our posts update automatically.

In HTML an input’s name attribute is sent over the network and available by the same name on the request’s formData. Oh, and don’t forget, the request and formData objects are both straight out of the web specification. So if you want to learn more about either of them, head over to MDN!

TypeScript is mad again, let’s add some types.

💿 Add the types to app/models/post.server.ts

  1. // ...
  2. import type { Post } from "@prisma/client";
  3. // ...
  4. export async function createPost(
  5. post: Pick<Post, "slug" | "title" | "markdown">
  6. ) {
  7. return prisma.post.create({ data: post });
  8. }

Whether you’re using TypeScript or not, we’ve got a problem when the user doesn’t provide values on some of these fields (and TS is still mad about that call to createPost).

Let’s add some validation before we create the post.

💿 Validate if the form data contains what we need, and return the errors if not

  1. import type { ActionArgs } from "@remix-run/node";
  2. import { json, redirect } from "@remix-run/node";
  3. import { Form } from "@remix-run/react";
  4. import { createPost } from "~/models/post.server";
  5. export const action = async ({ request }: ActionArgs) => {
  6. const formData = await request.formData();
  7. const title = formData.get("title");
  8. const slug = formData.get("slug");
  9. const markdown = formData.get("markdown");
  10. const errors = {
  11. title: title ? null : "Title is required",
  12. slug: slug ? null : "Slug is required",
  13. markdown: markdown ? null : "Markdown is required",
  14. };
  15. const hasErrors = Object.values(errors).some(
  16. (errorMessage) => errorMessage
  17. );
  18. if (hasErrors) {
  19. return json(errors);
  20. }
  21. await createPost({ title, slug, markdown });
  22. return redirect("/posts/admin");
  23. };
  24. // ...

Notice we don’t return a redirect this time, we actually return the errors. These errors are available to the component via useActionData. It’s just like useLoaderData but the data comes from the action after a form POST.

💿 Add validation messages to the UI

  1. import type { ActionArgs } from "@remix-run/node";
  2. import { redirect, json } from "@remix-run/node";
  3. import { Form, useActionData } from "@remix-run/react";
  4. // ...
  5. const inputClassName =
  6. "w-full rounded border border-gray-500 px-2 py-1 text-lg";
  7. export default function NewPost() {
  8. const errors = useActionData<typeof action>();
  9. return (
  10. <Form method="post">
  11. <p>
  12. <label>
  13. Post Title:{" "}
  14. {errors?.title ? (
  15. <em className="text-red-600">{errors.title}</em>
  16. ) : null}
  17. <input type="text" name="title" className={inputClassName} />
  18. </label>
  19. </p>
  20. <p>
  21. <label>
  22. Post Slug:{" "}
  23. {errors?.slug ? (
  24. <em className="text-red-600">{errors.slug}</em>
  25. ) : null}
  26. <input type="text" name="slug" className={inputClassName} />
  27. </label>
  28. </p>
  29. <p>
  30. <label htmlFor="markdown">
  31. Markdown:{" "}
  32. {errors?.markdown ? (
  33. <em className="text-red-600">
  34. {errors.markdown}
  35. </em>
  36. ) : null}
  37. </label>
  38. <br />
  39. <textarea
  40. id="markdown"
  41. rows={20}
  42. name="markdown"
  43. className={`${inputClassName} font-mono`}
  44. />
  45. </p>
  46. <p className="text-right">
  47. <button
  48. type="submit"
  49. className="rounded bg-blue-500 py-2 px-4 text-white hover:bg-blue-600 focus:bg-blue-400 disabled:bg-blue-300"
  50. >
  51. Create Post
  52. </button>
  53. </p>
  54. </Form>
  55. );
  56. }

TypeScript is still mad, because someone could call our API with non-string values, so let’s add some invariants to make it happy.

  1. //...
  2. import invariant from "tiny-invariant";
  3. // ..
  4. export const action = async ({ request }: ActionArgs) => {
  5. // ...
  6. invariant(
  7. typeof title === "string",
  8. "title must be a string"
  9. );
  10. invariant(
  11. typeof slug === "string",
  12. "slug must be a string"
  13. );
  14. invariant(
  15. typeof markdown === "string",
  16. "markdown must be a string"
  17. );
  18. await createPost({ title, slug, markdown });
  19. return redirect("/posts/admin");
  20. };

Progressive Enhancement

For some real fun, disable JavaScript in your dev tools and try it out. Because Remix is built on the fundamentals of HTTP and HTML, this whole thing works without JavaScript in the browser 🤯 But that’s not the point. What’s cool about it is that this means our UI is resilient to network issues. But we really like having JavaScript in the browser and there are a lot of cool things we can do when we’ve got it, so make sure to re-enable JavaScript before continuing, because we’re going to need it to progressively enhance the user experience next.

Let’s slow this down and add some “pending UI” to our form.

💿 Slow down our action with a fake delay

  1. // ...
  2. export const action = async ({ request }: ActionArgs) => {
  3. // TODO: remove me
  4. await new Promise((res) => setTimeout(res, 1000));
  5. // ...
  6. };
  7. //...

💿 Add some pending UI with useNavigation

  1. import type { ActionArgs } from "@remix-run/node";
  2. import { json, redirect } from "@remix-run/node";
  3. import {
  4. Form,
  5. useActionData,
  6. useNavigation,
  7. } from "@remix-run/react";
  8. // ..
  9. export default function NewPost() {
  10. const errors = useActionData<typeof action>();
  11. const navigation = useNavigation();
  12. const isCreating = Boolean(
  13. navigation.state === "submitting"
  14. );
  15. return (
  16. <Form method="post">
  17. {/* ... */}
  18. <p className="text-right">
  19. <button
  20. type="submit"
  21. className="rounded bg-blue-500 py-2 px-4 text-white hover:bg-blue-600 focus:bg-blue-400 disabled:bg-blue-300"
  22. disabled={isCreating}
  23. >
  24. {isCreating ? "Creating..." : "Create Post"}
  25. </button>
  26. </p>
  27. </Form>
  28. );
  29. }

Tada! You just implemented JavaScript-enabled progressive enhancement! 🥳 With what we’ve done, the experience is better than what the browser can do by itself. Lots of apps use JavaScript to enable the experience (and a select few actually do require JavaScript to work), but we’ve got a working experience as a baseline and just used JavaScript to enhance it.

Homework

That’s it for today! Here are some bits of homework to implement if you want to go deeper:

Update/Delete posts: make a posts.admin.$slug.tsx page for your posts. This should open an edit page for the post that allows you to update the post or even delete it. The links are already there in the sidebar, but they return 404! Create a new route that reads the posts, and puts them into the fields. All the code you need is already in app/routes/posts.$slug.tsx and app/routes/posts.admin.new.tsx. You just gotta put it together.

Optimistic UI: You know how when you favorite a tweet, the heart goes red instantly and if the tweet is deleted it reverts back to empty? That’s Optimistic UI: assume the request will succeed, and render what the user will see if it does. So your homework is to make it so when you hit “Create” it renders the post in the left nav and renders the “Create a New Post” link (or if you add update/delete do it for those too). You’ll find this ends up being easier than you think even if it takes you a second to arrive there (and if you’ve implemented this pattern in the past, you’ll find Remix makes this much easier). Learn more from the Optimistic UI guide.

Authenticated users only: Another cool bit of homework you could do is make it so only authenticated users can create posts. You’ve already got authentication all set up for you thanks to the Indie Stack. Tip: if you want to make it so you’re the only one who can make posts, simply check the user’s email in your loaders and actions and if it’s not yours redirect them somewhere 😈

Customize the app: If you’re happy with Tailwind CSS, keep it around, otherwise, check the styling guide to learn of other options. Remove the Notes model and routes, etc. Whatever you want to make this thing yours.

Deploy the app: Check the README of your project. It has instructions you can follow to get your app deployed to Fly.io. Then you can actually start blogging!

We hope you love Remix! 💿 👋