File attachment in Xata Database: How to build an Online Library.
Tags: xata, webdev, database, nextjs
Published: 2023-09-24 16:47:51

## Introduction.

Files and attachments are the core of information distribution in the digital ecosystem, in a relational database, file attachment is a way of structuring the database to meet the needs of the product. A badly structured database usually results in more development time and errors. This is one of the problems that file attachments in Xata Database aim to solve by removing the clumsiness of the database and making it more simplified and structured.

## So, what’s up Xata?

[Xata](xata.io) is a serverless database platform that provides database optimization in development, providing an easy workflow for web development, with Xata database, developers do not need to worry about scaling, downtime prevention, and database maintenance.

To follow along with this guide, the following are the prerequisites needed;

- A Xata Database user account.
- Knowledge of JavaScript.
- Knowledge of React or NextJjs for frontend development.

File attachments make it easy to store data more efficiently and in an organized manner, meaning that you do not need extra external services for file storage in your database, and you also get to view these files in their original forms, in this blog post, we will build an online library and learn how to attach files to our library database.

With Xata file attachment feature, you can easily save documents of different types, images, videos and other files of your choice on your database without any external file storage services.

### Benefits of using Xata File attachment feature includes the following;

- With Xata file attachments, you reduce the latency of your project to the barest minimum, Xata allows this by providing built-in CDN capabilities for your file attachments, meaning that your file attachments are fetched along with other records in your database, and you don't need any extra settings to get this up and running, ease of development has always been the focus of the Xata team.
- Your relational data and binary objects will be saved in the same data region, and you won't be concerned with compliance boundaries.
- Your Database APIs now have the same permissions and authorization, keeping your credentials and permissions the same, this reduces the complexity of authorizations on the client side.
- The ability to apply different image transformations to your image files through the same API that points to your data records. with Xata file attachments, image preprocessing before rendering is a thing of the past, you can easily apply several image transformations, ranging from image format change to photo resizing, all depending on your specific needs,

### Let’s create our Xata database in the following steps:

1. Create a `Database` named `library` as seen below.
![workspace](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t2l97e30vbpyoql6qw7v.jpg)
2. Create a database schema by adding a table, inside the table, add the following columns, recall that we have two file types that we want to include in our database, which are the `book cover image` and the `book file` itself.

- book-name.
- author.
- size.
- image.
- bookfile.

Let us attach our files to our library’s database in the following steps:

1. On the Admin page of our database, click on `add record` to add a new book record and its details, as seen below.
![record](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fdb3dcdi2rfxw21tal5h.png)
2. For the two file columns, which are `book cover image` and `bookfile`, click on the `Add files` button to select the appropriate files from your local storage.
3. Click on the `create record` `button`, and you will see the new record attached to our database as shown below.
![add-record](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/aj0hiivczud7fbfk3plm.jpg)
That’s all with file attachments in the Xata Database, let’s go ahead and display our data on our Next.Js App.

### Let's move on to the Next thing, which is Next.Js.

To get started with our App, create a Next App using the following code snippet:

`npx create-next-app@latest --your-app-name`

During installation, accept all prompts and set your app to the default settings.

Once your app is installed, run `npm run dev` to start your development server, and locate your server at http://localhost:3000/.  Let us build our App’s structure and give it a little styling for the purpose of this tutorial. Add the following React code to your file to follow along; we will display the book’s name, book author, book size, cover image, and book file on our website, as seen in the React code block below.

```tsx
import Link from "next/link";
import Image from "next/image";

export default async function Home() {

  return (
    <main className="sm:flex grid items-center justify-between p-5">
          <div className="mx-5 my-10 " key={books.id}>
            <div className="h-[350px] w-[300px] bg-blue-300">
              <div className="">
                <div className=" my-5 mr-5">Book:{books["book-name"]}</div>
              </div>
              <div>
                <div className="my-5 mr-5"> Author: {books.author}</div>
              </div>
              <div>
                <div className="my-5 mr-5">Size: {books.size}</div>
              </div>

              <div>
                <div className="my-5 mr-5">
                  Image:
                  {books.image && (
                    <img
                      src={books.image[0].url}
                      className="h-[120px] w-[120px]"
                      alt={`Image for ${books["book-name"]}`}
                    />
                  )}
                </div>
              </div>
              <div>
                <div className="my-5 mr-5">
                  <button className="bg-red-300 p-1">
                    <Link
                      href={books.bookfile[0].url}
                      target="_blank"
                      rel="noopener noreferrer"
                    >
                      download
                    </Link>
                  </button>
                </div>
              </div>
            </div>
          </div>
    </main>
  );
}
```
The next step is to initialize our library database in the NextJs project and fetch data from our Database and render the data in our App. To fetch data from the database, follow the following steps:
1.To get started with Xata Database in your NextJs project, install Xata using the Command Line Interface (CLI), and authenticate with your Xata account using the code block below:
```bash
npm i -g @xata.io/cli
xata auth login 
xata init
```
Follow the prompts, and your Xata database will be connected to your project, as seen below:
![xatasetup](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o5ve81wsnkwmqun4j8h1.jpg)

2.After your database is set up with your project, import `getXataClient` from the directory where you saved it as seen in the code snippet below:
```tsx
import { getXataClient } from "@/utils/xata";
```
3.Create a constant for your XataClient using the following code snippet:
```tsx
const xata = getXataClient();
```
4.Run the code snippet below to query your library database:
```tsx
const library = await xata.db.library.getMany();
```
5.Serialize your library database and return it as a JavaScript object using the following code block:
```tsx
const serializedLibraryData = JSON.stringify(library);
const DeserializedLibraryData = JSON.parse(serializedLibraryData);
```

Once the codes above are run successfully, you will have access to your library database and the attached files all in your code editor, the final work of JavaScript is to map over the data and render it dynamically on the website. 

To map over the library database, use the following JavaScript code snippet:

The code snippet will check if the deserialized is available on the database, and also make sure that the length of the deserialized data is more than zero, afterwards, it maps over the data accordingly. 

```
{DeserializedLibraryData &&
        DeserializedLibraryData.length > 0 &&
        DeserializedLibraryData.map((books) => ())}
```

And that's a wrap, now refresh your browser to have up-to date website content and functionality where the public can download any of the books available on the website.

At any point in time, when you make changes to your database on the web UI, run `xata pull main`  and restart your development server to incorporate the changes in your local project file.

## Conclusion.

Web development software and projects are the pipeline of data management, and as such, good web projects using simplified and well structured database management should be encouraged for ease of development and exactly this is what Xata serverless database is all about.
In this blog post we have learnt about File attachments in Xata database and built a client facing online library, to build more exciting projects using Xata database, this guide is enough a starter for both experienced and upcoming developers.
Attached is a screenshot of the website's interface.

![library](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y40w6xt72kskedobafxe.jpg)
Link to the github repository for the project is [here](https://github.com/AbuTuraab/online-library). 
You can also read more on Xata documentation [here](https://xata.io/docs/concepts/file-attachments).