Get started with Remix and Xata
In this guide, you'll learn how to add Xata database and search functionality to a Remix application. You'll build the following basic blog application features:
- List all blog posts
- Retrieve and view a single blog post
- Full-text fuzzy search of blog posts
Although this application is a simple blog, you can apply these basics to other types of Remix applications.
The completed Remix and Xata code for this
guide is available via the Xata examples
repo on GitHub.
Install the Xata CLI:
npm install -g @xata.io/cli
npm install -g '@xata.io/cli'
Once installed, authenticate the Xata CLI with your Xata account. If you don't already have an account, you can use the same workflow to sign up for a new account. Run the following command to begin the authentication workflow:
xata auth login
On completion, the command will create a new API key for your user account, which you should see in the account settings page within the Xata UI. That key will also be stored locally on your computer (the location might vary for each OS). It looks like this:
# .config/xata/credentials
[default]
apiKey=YOUR_API_KEY_HERE
Begin by creating a new Remix application, accepting the default prompt options:
npx create-remix@latest xata-remix
Once the command has completed, go to the xata-remix
directory and run the application:
cd xata-remix
npm run dev
By default, the application will run on http://localhost:3000
.
Once you have the Xata CLI installed, are logged in, and have set up a new Remix application, you are ready to use the Xata CLI to generate a new database. Accept all the prompt defaults for the following command except for the region selection where you should choose the region closest to your application users:
xata init
On completion, the CLI will create .env
, .xatarc
, and src/xata.ts
files within your project folder with the
correct credentials to access your database.
Your .env
file should look something like this:
XATA_API_KEY=YOUR_API_KEY_HERE
XATA_BRANCH=main
Since you selected TypeScript support, it also created files that provide typings and functions to call using Xata's
TypeScript SDK. This will additionally be referenced in the .xatarc
file as follows:
{
"databaseUrl": "https://my-xata-app-database-url",
"codegen": {
"output": "src/xata.ts"
}
}
The src/xata.ts
file includes generated code you should typically never touch manually.
You can use the Xata UI to manually define your schema and add data. However, for this guide, you'll use the Xata CLI and a CSV file to:
- Auto-generate a schema based on column headings for names and data types inferred from the column values
- Import data to the database
First, download the example blog posts CSV file. You can either do this manually or by running the following command:
curl --create-dirs -o seed/blog-posts.csv https://raw.githubusercontent.com/xataio/examples/main/seed/blog-posts.csv
curl.exe --create-dirs -o seed/blog-posts.csv https://raw.githubusercontent.com/xataio/examples/main/seed/blog-posts.csv
Next, import the CSV:
xata import csv seed/blog-posts.csv --table Posts --create
Now, if you open up the Xata UI and navigate to your database, you will see the Posts table. Alternatively,
you can run the command xata browse
to open a browser window:
Click Schema to see the schema definition with the inferred data types:
You'll also see xata.*
special columns automatically
created and maintained by Xata.
With the database schema in place, the final step is to generate the code that allows you to access and query the data from our Remix application. To do this, run:
xata pull main
This updates the contents of src/xata.ts
based on the schema defined on the main
branch of your database. So, if you
make any further changes to the schema, run xata pull <branch>
to update the auto-generated code.
The first step to add some styling to the application is to add Tailwind CSS. To do that, follow the official Remix and Tailwind CSS guide.
Once all the steps from the guide have been followed, update app/tailwind.css
with some additional rules:
@tailwind base;
@tailwind components;
@tailwind utilities;
:root {
--foreground-rgb: 0, 0, 0;
--background-start-rgb: 214, 219, 220;
--background-end-rgb: 255, 255, 255;
}
@media (prefers-color-scheme: dark) {
:root {
--foreground-rgb: 255, 255, 255;
--background-start-rgb: 0, 0, 0;
--background-end-rgb: 0, 0, 0;
}
}
body {
color: rgb(var(--foreground-rgb));
background: linear-gradient(to bottom, transparent, rgb(var(--background-end-rgb))) rgb(var(--background-start-rgb));
}
Finally, update app/root.tsx
to add some shared structure across application pages. The code will end up as follows:
import type { LinksFunction } from '@remix-run/node';
import { Links, LiveReload, Meta, Outlet, Scripts, ScrollRestoration } from '@remix-run/react';
import styles from './tailwind.css';
export const links: LinksFunction = () => [{ rel: 'stylesheet', href: styles }];
export default function App() {
return (
<html lang="en">
<head>
<meta charSet="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<Meta />
<Links />
</head>
<body>
<main className="flex flex-col items-center p-8 lg:p-24 min-h-screen">
<div className="z-10 h-50 w-full max-w-5xl items-center justify-between text-xl lg:flex">
<p className="fixed left-0 top-0 flex w-full justify-center pb-6 pt-8 lg:static lg:w-auto bg-gradient-to-b from-white via-white via-65% dark:from-black dark:via-black lg:bg-none">
<a href="/">Get started with Xata</a>
</p>
<div className="fixed bottom-0 left-0 flex w-full items-end justify-center bg-gradient-to-t from-white via-white dark:from-black dark:via-black lg:static lg:h-auto lg:w-auto lg:bg-none">
<a href="https://xata.io" className="w-20">
<img src="https://raw.githubusercontent.com/xataio/examples/main/docs/app_logo.svg" />
</a>
</div>
</div>
<Outlet />
</main>
<ScrollRestoration />
<Scripts />
<LiveReload />
</body>
</html>
);
}
Ensure the <Outlet />
component is before the closing </main>
element.
Now, you're ready to integrate Xata into the Remix codebase. Start by stripping back the landing page,
app/routes/_index.tsx
, to a bare template:
import { MetaFunction } from '@remix-run/node';
export const meta: MetaFunction = () => {
return [{ title: 'Xata and Remix' }];
};
export default function Index() {
return (
<>
<div className="w-full max-w-5xl mt-16"></div>
</>
);
}
Next, update the page to get all the posts using Xata, and list them within the page:
import { MetaFunction, json } from '@remix-run/node';
import { useLoaderData } from '@remix-run/react';
import { getXataClient } from 'src/xata';
export const meta: MetaFunction = () => {
return [{ title: 'Xata and Remix' }];
};
export async function loader() {
const xata = getXataClient();
const posts = await xata.db.Posts.getAll();
return json({
posts
});
}
export default function Index() {
const { posts } = useLoaderData<typeof loader>();
return (
<>
<div className="w-full max-w-5xl mt-16">
{posts.length === 0 && <p>No blog posts found</p>}
{posts.map((post) => (
<div key={post.id} className="mb-16">
<p className="text-xs mb-2 text-purple-950 dark:text-purple-200">
{new Date(post.pubDate || '').toDateString()}
</p>
<h2 className="text-2xl mb-2">
<a href={`posts/${post.slug}`}>{post.title}</a>
</h2>
<p className="text-purple-950 dark:text-purple-200 mb-5">{post.description}</p>
<a
href={`posts/${post.slug}`}
className="px-4 py-2 font-semibold text-sm bg-purple-700 text-white rounded-lg shadow-sm w-fit"
>
Read more →
</a>
</div>
))}
</div>
</>
);
}
Here's a breakdown of what's happening in the code above.
First, update the @remix-run/node
to also bring in json
, and a new import from
@remix-run/react
is introduced to bring in useLoaderData
. The details of how those are used
will be covered shortly. The auto-generated getXataClient
is also imported.
import { MetaFunction, json } from '@remix-run/node';
import { useLoaderData } from '@remix-run/react';
import { getXataClient } from 'src/xata';
Next, a Remix framework server-only loader
function is defined
and exported. This function provides data to the route when rendering. Within that function, an instance of the XataClient
is created using getXataClient
and assigned to the xata
variable. Then, use the xata
client instance
to get all the posts stored in the database. This is achieved via the auto-generated Posts
property,
which exposes a number of helper functions. In this case, use the
getAll
function to get
all the Post records. Finally, return the posts making use of the imported Remix json
helper function.
export async function loader() {
const xata = getXataClient();
const posts = await xata.db.Posts.getAll();
return json({
posts
});
}
getAll()
returns all the records in the query results. This is dangerous on large tables (more than 10,000 records),
as it will potentially load a lot of data into memory and create a lot of requests to the server. In most situations,
you should use getMany()
or getPaginated()
. See the querying
documentation for more information.
Finally, within the Index
function, use the useLoaderData
Remix hook
retrieve the posts
data.
Then, update the UI to display the results. If no records are present, show a message
saying, "No blog posts found". Otherwise, loop through the posts
using posts.map
and access the columns of
each Post record using their properties: id
as a unique identifier for the key
attribute, pubDate
to show the date
the blog post was published, slug
to link to individual blog posts (which will be used use later), title
for the title of
the post, and description
for the textual description of the post. Since pubData
has been serialized to a string, convert
it back into a Date
and then use .toDateString()
to get a slightly nicer formatted date representation for the UI:
export default function Index() {
const { posts } = useLoaderData<typeof loader>();
return (
<>
<div className="w-full max-w-5xl mt-16">
{posts.length === 0 && <p>No blog posts found</p>}
{posts.map((post) => (
<div key={post.id} className="mb-16">
<p className="text-xs mb-2 text-purple-950 dark:text-purple-200">
{new Date(post.pubDate || '').toDateString()}
</p>
<h2 className="text-2xl mb-2">
<a href={`posts/${post.slug}`}>{post.title}</a>
</h2>
<p className="text-purple-950 dark:text-purple-200 mb-5">{post.description}</p>
<a
href={`posts/${post.slug}`}
className="px-4 py-2 font-semibold text-sm bg-purple-700 text-white rounded-lg shadow-sm w-fit"
>
Read more →
</a>
</div>
))}
</div>
</>
);
}
This results in the page looking like the following:
You'll notice that the post heading and "Read more →" text use the slug
property to link to a page that doesn't
presently exist. That's the next step in this guide.
To handle the single posts identified by a slug
, make use of Remix
dynamic segments.
Create a new file, app/routes/posts.$slug.tsx
, where the Remix framework uses the filename segment $slug
to capture
the name of the slug:
import { LoaderFunctionArgs, MetaFunction, json } from '@remix-run/node';
import { useLoaderData } from '@remix-run/react';
import { getXataClient } from 'src/xata';
export async function loader({ params }: LoaderFunctionArgs) {
const xata = getXataClient();
const post = await xata.db.Posts.filter({ slug: params.slug }).getFirst();
return json({
post
});
}
export const meta: MetaFunction<typeof loader> = ({ data }) => {
return [{ title: `${data?.post?.title} - Xata and Remix` }];
};
export default function Post() {
const { post } = useLoaderData<typeof loader>();
return (
<div className="w-full max-w-5xl mt-16">
<p className="mb-2">
<a href="/" className="text-purple-600">
← Back to blog
</a>
</p>
<h1 className="text-3xl mb-2">{post?.title}</h1>
<p className="text-sm mb-4 text-purple-950 dark:text-purple-200">
{new Date(post?.pubDate ?? '').toDateString()}
</p>
<p className="text-xl">{post?.description}</p>
</div>
);
}
Let's walk through what this does.
The imports are mostly the same as the landing page with the addition of the LoaderFunctionArgs
import:
import { LoaderFunctionArgs, MetaFunction, json } from '@remix-run/node';
import { useLoaderData } from '@remix-run/react';
import { getXataClient } from 'src/xata';
The loader
function does the same job as the landing page but is updated to take parameters of type LoaderFunctionArgs
.
The params
property on LoaderFunctionArgs
gives you the slug value from the URL via params.slug
.
Use the getXataClient
function to get a Xata client instance, and then use the
filter
function on the
auto-generated Posts
property to perform a query on the Posts table and find the
record where the slug
column equals the value of params.slug
. Use the
getFirst
function to access
the first (and only) Post result and return the post, again using the Remix json
help function.
export async function loader({ params }: LoaderFunctionArgs) {
const xata = getXataClient();
const post = await xata.db.Posts.filter({ slug: params.slug }).getFirst();
return json({
post
});
}
In case you encounter a "Runtime.UnhandledPromiseRejection"
when deploying the Remix app, try passing the Remix fetch implementation to the XataClient.
import { fetch as webFetch } from "@remix-run/web-fetch";
import { XataClient } from "src/xata";
const xata = new XataClient({
fetch: webFetch,
});
Use the values returned from the loader
within the MetaFunction
function to display the Post's title
within the page's title. This function differs from the landing page version by taking a parameter containing a data
property.
The value in data
is the payload returned from the loader
function. So, the Post's title
value can be extracted and used:
export const meta: MetaFunction<typeof loader> = ({ data }) => {
return [{ title: `${data?.post?.title} - Xata and Remix` }];
};
Finally, the main page function makes use of the userLoaderData
hook to retrieve the single Post information and uses the values,
title
, pubDate
, and description
, for the Post are added to the UI:
export default function Post() {
const { post } = useLoaderData<typeof loader>();
return (
<div className="w-full max-w-5xl mt-16">
<p className="mb-2">
<a href="/" className="text-purple-600">
← Back to blog
</a>
</p>
<h1 className="text-3xl mb-2">{post?.title}</h1>
<p className="text-sm mb-4 text-purple-950 dark:text-purple-200">
{new Date(post?.pubDate ?? '').toDateString()}
</p>
<p className="text-xl">{post?.description}</p>
</div>
);
}
The single blog post page will look as follows:
The last piece of functionality to add to the application is full-text fuzzy search of blog posts.
When you insert data into a Xata database, it is automatically indexed for full-text search. So you don't need to change any configuration to enable search, just need to use the TypeScript SDK search feature.
Let's add this functionality to the landing page:
import { LoaderFunctionArgs, MetaFunction, json } from '@remix-run/node'
import { useLoaderData } from '@remix-run/react'
import { getXataClient } from 'src/xata'
...
export async function loader({ request }: LoaderFunctionArgs) {
const xata = getXataClient()
const url = new URL(request.url)
const search = url.searchParams.get('q')
let posts = null
if (search) {
posts = await xata.db.Posts.search(search, { fuzziness: 2 })
} else {
posts = await xata.db.Posts.getAll()
}
return json({
posts,
search,
})
}
export default function Index() {
const { posts, search } = useLoaderData<typeof loader>()
return (
<>
<div className="w-full max-w-5xl mt-16">
<form>
<input
name="q"
defaultValue={search || ''}
placeholder="Search..."
className="w-full rounded-lg p-2 border-2 dark:text-purple-950"
/>
</form>
</div>
...
</>
)
}
Here's a breakdown of what's happening in the code above.
First, update the @remix-run/node
import to include LoaderFunctionArgs
. Then, update the loader
function to accept
the request
property from the LoaderFunctionArgs
parameter.
import { LoaderFunctionArgs, MetaFunction, json } from '@remix-run/node'
import { useLoaderData } from '@remix-run/react'
import { getXataClient } from 'src/xata'
...
export async function loader({ request }: LoaderFunctionArgs) {
...
}
Next, update the loader
function to conditionally perform a search based on the presence of search text within a q
querystring parameter.
Do this by creating a new URL
instance and passing the request.url
value. Then, get the q
querystring using url.searchParams.get('q')
and assign the result to a variable called search
.
The landing page should list all blog posts if search
is an empty string. However, if
the search has a non-empty string value, a search is performed on the Posts table using the
search
function exposed on the
auto-generated Posts
property. Pass search
as the text value to search for, and use a
second options parameter with fuzziness
set to 2
, which informs the fuzzy search behavior to allow for two
letters changed/added/removed. See
fuzziness and typo tolerance for more
details.
Update the return value of loader
to return both posts
and search
.
export async function loader({ request }: LoaderFunctionArgs) {
const xata = getXataClient();
const url = new URL(request.url);
const search = url.searchParams.get('q');
let posts = null;
if (search) {
const { records } = await xata.db.Posts.search(search, { fuzziness: 2 });
posts = records;
} else {
posts = await xata.db.Posts.getAll();
}
return json({
posts,
search
});
}
The last change enables the user to input and submit a search.
Begin by retrieving the posts
and the search
values using the Remix userLoaderData
hook.
Next, add a <form>
to the page to allow a search value to be entered and submitted. The
default behavior of a form is to submit a GET
request to the current URL with any form inputs added to the query
string in the format {url}/?{input-name}={input-value}
. For our search form, the result of a form submission is
a GET
request in the format ?q={q-value}
. Since this is precisely the behavior required, and the check for the q
querystring search value has been implemented already, everything is in place.
export default function Index() {
const { posts, search } = useLoaderData<typeof loader>();
return (
<>
<div className="w-full max-w-5xl mt-16">
<form>
<input
name="q"
defaultValue={search || ''}
placeholder="Search..."
className="w-full rounded-lg p-2 border-2 dark:text-purple-950"
/>
</form>
</div>
...
</>
);
}
The application now supports listing posts, viewing single posts via a dynamic segment, and full-text fuzzy search of posts.
In this guide, you've learned that Remix applications and Xata are a powerful combination. You created an application from scratch that lists blog posts, supports viewing a single blog post, and performs full-text fuzzy search on all posts.
You walked through setting up the Xata CLI and using it to:
- Create a new Xata project
- Create a database schema and populate it with data from an imported CSV file
- Update the auto-generated code (in
src/xata.ts
) usingxata pull main
to reflect the updated schema
You then updated the landing page to list all blog posts, making use of the auto-generated xata.db.Posts.getAll
function. You also added the single post page making use of Remix dynamic segments where a slug
was passed and used
with xata.db.Posts.filter({ slug: params.slug }).getFirst()
.
Finally, you added full-text fuzzy search functionality to the landing page, leveraging Xata's automatic table
indexing. The search used a q
query string and the auto-generated xata.db.Posts.search
function.
If you enjoyed this guide, you could continue working on improving the application. Here are some suggestions:
- Add pagination for the blog post listing
- Add pagination for blog post search results
- Handle single post view page not finding a result for a
slug
- Add a
body
field to the database schema to contain the full text of the blog post and update the single page view to use that new field
You can also explore some of the features covered in more detail:
Or dive into some of Xata's more advanced features, such as: