Unverified Commit 2fa33b35 authored by Atila Fassina's avatar Atila Fassina Committed by GitHub

Add `with-xata` example (#39864)

This Pull Request adds a `with-xata` example to use [Xata](https://xata.io) as the data layer of a Next.js app.

## Documentation / Examples

- [x] Make sure the linting passes by running `pnpm lint`
- [x] The examples guidelines are followed from [our contributing doc](https://github.com/vercel/next.js/blob/canary/contributing.md#adding-examples)
Co-authored-by: 's avatarBalázs Orbán <18369201+balazsorban44@users.noreply.github.com>
parent 06607e3d
# See http://help.github.com/ignore-files/ for more about ignoring files.
# compiled output
/build
/out
/dist
/tmp
/out-tsc
# dependencies
/node_modules
# IDEs and editors
/.idea
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace
# IDE - VSCode
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
# misc
/.sass-cache
/connect.lock
/coverage
/libpeerconnection.log
npm-debug.log
yarn-error.log
testem.log
/typings
# System Files
.DS_Store
Thumbs.db
.next
.turbo
node_modules
**/.xatarc
.env
.env.*
\ No newline at end of file
# Next.js + Xata
This example showcases how to use Next.js with [Xata](https://xata.io) as your data layer.
With this template you get out-of-the-box:
- API Route to connect to your Xata database
- Type-safe Codegen
- Accessibility-Ready
- Dark/Light mode
- Respects `prefers-reduce-motion` for CSS Transitions
## Deploy your own
Deploy the example using [Vercel](https://vercel.com?utm_source=github&utm_medium=readme&utm_campaign=next-example) or preview live with [StackBlitz](https://stackblitz.com/github/vercel/next.js/tree/canary/examples/with-xata)
[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/git/external?repository-url=https://github.com/vercel/next.js/tree/canary/examples/with-xata&project-name=with-xata&repository-name=with-xata)
## Demo
[nextjs-with-xata.vercel.app](https://nextjs-with-xata.vercel.app)
## How to use
Execute [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app) with [npm](https://docs.npmjs.com/cli/init), [Yarn](https://yarnpkg.com/lang/en/docs/cli/create/), or [pnpm](https://pnpm.io) to bootstrap the example:
```sh
npx create-next-app --example cms-contentful cms-contentful-app
```
```sh
yarn create next-app --example cms-contentful cms-contentful-app
```
```sh
pnpm create next-app --example cms-contentful cms-contentful-app
```
### Link Your Xata Workspace and Run Codegen
> 💡 consider [installing the Xata CLI globally](https://xata.io/docs/cli/getting-started), it will likely improve your experience managing your databases
```sh
npm run start:xata
```
> ⚠️ once linked, you can just run `xata` to re-generate types.
### Start Coding
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
> 💡 the template will prompt you to create a dummy new table (`nextjs_with_xata_example`) with some useful resources.
## Notes
Some tips that may help you develop your app.
- The Xata [VS Code Extension](https://marketplace.visualstudio.com/items?itemName=xata.xata) will make managing your data more comfortable
- Prefer fetching data from `getServerSideProps()` or `getStaticProps()`
- Create a Serverless Route(s) to handle data mutations
Deploy it to the cloud with [Vercel](https://vercel.com/new?utm_source=github&utm_medium=readme&utm_campaign=next-example) ([Documentation](https://nextjs.org/docs/deployment)).
/// <reference types="next" />
/// <reference types="next/image-types/global" />
// NOTE: This file should not be edited
// see https://nextjs.org/docs/basic-features/typescript for more information.
{
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"start:xata": "xata init --schema=schema.template.json --codegen=utils/xata.codegen.ts",
"poststart:xata": "xata codegen",
"xata": "xata codegen"
},
"devDependencies": {
"@types/node": "18.6.5",
"@types/react": "18.0.17",
"@types/react-dom": "18.0.6",
"@xata.io/cli": "0.8.1",
"eslint": "8.21.0",
"eslint-config-next": "latest",
"typescript": "4.7.4"
},
"dependencies": {
"@xata.io/client": "^0.16.1",
"next": "latest",
"react": "^18.2.0",
"react-dom": "^18.2.0"
}
}
import type { AppProps } from 'next/app'
import Head from 'next/head'
import '../styles/root.css'
const metas = {
title: 'Next.js with-xata',
description: 'Run Next.js with Xata with this awesome template',
image:
process.env.NODE_ENV === 'development'
? 'http://localhost:3000/og.jpg'
: 'https://nextjs-with-xata.vercel.app/og.jpg',
}
export default function App({ Component, pageProps }: AppProps) {
return (
<>
<Head>
<title>{metas.title}</title>
<meta property="og:title" content={metas.title} key="og:title" />
<meta property="og:image" content={metas.image} key="og:image" />
<meta
property="description"
content={metas.description}
key="description"
/>
<meta
property="og:description"
content={metas.description}
key="og:description"
/>
<meta property="og:type" content="website" />
<meta property="twitter:card" content="summary_large_image" />
<meta
property="twitter:title"
content={metas.title}
key="twitter:title"
/>
<meta
property="twitter:description"
content={metas.description}
key="twitter:description"
/>
<meta
property="twitter:image"
content={metas.image}
key="twitter:image"
/>
<meta
name="theme-color"
content="#000"
media="(prefers-color-scheme: dark)"
/>
<meta
name="theme-color"
content="#fff"
media="(prefers-color-scheme: light)"
/>
</Head>
<Component {...pageProps} />
</>
)
}
import type { NextApiRequest, NextApiResponse } from 'next'
import { getXataClient } from '../../utils/xata.codegen'
const xata = getXataClient()
const deleteItem = async (id: string) => {
return await xata.db.nextjs_with_xata_example.delete(id)
}
export async function cleanDummyDataFromXata(
req: NextApiRequest,
res: NextApiResponse
) {
const { id } = req.body
await deleteItem(id)
res.json({
ok: true,
})
}
export default cleanDummyDataFromXata
import type { NextApiRequest, NextApiResponse } from 'next'
import { getXataClient } from '../../utils/xata.codegen'
const LINKS = [
{
description: 'Everything you need to know about Xata APIs and tools.',
title: 'Xata Docs',
url: 'https://xata.io/docs',
},
{
description: 'In case you need to check some Next.js specifics.',
title: 'Next.js Docs',
url: 'https://nextjs.org/docs',
},
{
description:
'Maintain your flow by managing your Xata Workspace without ever leaving VS Code.',
title: 'Xata VS Code Extension',
url: 'https://marketplace.visualstudio.com/items?itemName=xata.xata',
},
{
description: 'Get help. Offer help. Show us what you built!',
title: 'Xata Discord',
url: 'https://xata.io/discord',
},
]
const xata = getXataClient()
export default async function writeLinksToXata(
_req: NextApiRequest,
res: NextApiResponse
) {
await xata.db.nextjs_with_xata_example.create(LINKS)
res.json({
ok: true,
})
}
import type { InferGetServerSidePropsType } from 'next'
import Image from 'next/image'
import { getXataClient } from '../utils/xata.codegen'
import xatafly from '../public/xatafly.gif'
const pushDummyData = async () => {
const response = await fetch('/api/write-links-to-xata')
if (response.ok) {
window?.location.reload()
}
}
const removeDummyItem = async (id: string) => {
const { status } = await fetch('/api/clean-xata', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ id }),
})
if (status === 200) {
window?.location.reload()
}
}
export default function IndexPage({
links,
}: InferGetServerSidePropsType<typeof getServerSideProps>) {
return (
<main>
<header>
<Image src={xatafly} priority />
<h1>
Next.js with<span aria-hidden>&#8209;</span>xata
</h1>
</header>
<article>
{links.length ? (
<ul>
{links.map(({ id, title, url, description }) => (
<li key={url}>
<a href={url} rel="noopener noreferrer" target="_blank">
{title}
</a>
<p>{description}</p>
<button
type="button"
onClick={() => {
removeDummyItem(id)
}}
>
<span role="img" aria-label="delete item">
🗑
</span>
</button>
</li>
))}
</ul>
) : (
<section>
<h2>No records found.</h2>
<strong>
Create a `nextjs_with_xata_example` and push some useful links to
see them here.
</strong>
<button
type="button"
onClick={() => {
pushDummyData()
}}
>
Push records to Xata
</button>
</section>
)}
</article>
<footer>
<span>
Made by{' '}
<a href="https://xata.io" rel="noopener noreferrer" target="_blank">
<object data="/xatafly.svg" />
</a>
</span>
</footer>
</main>
)
}
export const getServerSideProps = async () => {
const xata = await getXataClient()
const links = await xata.db.nextjs_with_xata_example.getAll()
return {
props: {
links,
},
}
}
This diff is collapsed.
<svg viewBox="0 0 461 467" fill="none" xmlns="http://www.w3.org/2000/svg">
<style>
@media (prefers-color-scheme: dark) {
path {
fill: white;
}
}
@media (prefers-color-scheme: light) {
path {
fill: black;
}
}
svg {
transition: fill 250ms linear;
cursor: pointer;
}
svg:hover .green {fill: #06D6A0 }
svg:hover .yellow { fill: #FFBB00 }
svg:hover .magenta { fill: #FF0075 }
svg:hover .blue { fill: #0076FF }
</style>
<path class="green" d="M389.431 465.611C421.673 433.443 443.246 393.222 449.403 353.796C455.56 314.369 445.797 278.966 422.262 255.376L300.691 376.663L389.431 465.611Z"/>
<path class="yellow" d="M71.5738 466.306C39.331 434.138 17.7582 393.917 11.6011 354.49C5.44395 315.064 15.2069 279.661 38.7422 256.07L160.314 377.358L71.5738 466.306Z"/>
<path class="magenta" d="M0.673946 122.184C0.727229 167.729 18.8709 211.387 51.1137 243.554L51.1168 243.551L172.673 364.823C204.84 332.58 222.882 288.88 222.829 243.335C222.775 197.79 204.632 154.132 172.389 121.964L172.386 121.967L50.8296 0.695312C18.6622 32.9381 0.620662 76.6388 0.673946 122.184Z"/>
<path class="blue" d="M460.329 121.488C460.276 167.033 442.132 210.692 409.89 242.859L409.886 242.855L288.33 364.127C256.163 331.884 238.121 288.183 238.175 242.638C238.228 197.094 256.372 153.435 288.614 121.268L288.618 121.271L410.174 0C442.341 32.2428 460.383 75.9435 460.329 121.488Z"/>
</svg>
{
"formatVersion": "",
"tables": [
{
"name": "nextjs_with_xata_example",
"columns": [
{
"name": "title",
"type": "string"
},
{
"name": "description",
"type": "string"
},
{
"name": "url",
"type": "string"
}
]
}
]
}
html {
--system-fonts: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto,
Helvetica, Arial, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji',
'Segoe UI Symbol';
--xata-accent: rgb(255, 0, 117);
--xata-accent-faded: rgba(255, 0, 117, 0.4);
--transition-duration: 350ms;
--background-color: #000;
--text-color: #fff;
}
body {
padding: 0;
margin: 0;
min-height: 100vh;
overflow-x: hidden;
font-family: 'Inter', var(--system-fonts);
color: var(--text-color);
background-color: var(--background-color);
}
h1 {
font-family: monospace;
font-size: 3rem;
text-align: center;
}
img {
width: 300px;
}
a,
li {
transition: all var(--transition-duration) ease-in-out;
}
a {
color: var(--text-color);
font-size: 2rem;
text-decoration: none;
}
a:hover,
a:focus {
text-decoration: underline dotted;
color: var(--xata-accent);
}
li a[target='_blank']::after {
content: '↗';
position: relative;
top: -1em;
left: 0.5em;
font-size: 1rem;
}
p {
color: var(--text-color);
font-size: 1.2rem;
line-height: 2;
}
main {
min-height: 100vh;
display: grid;
grid-template-rows: auto 1fr auto;
}
header,
footer {
display: grid;
place-items: center;
}
header {
height: clamp(4rem, 40rem, 55vh);
}
footer {
border-top: dashed 2px rgba(255, 255, 255, 0.4);
height: clamp(2rem, 5rem, 10vh);
}
section {
display: grid;
place-items: center;
max-width: 70vw;
padding: 5rem;
grid-gap: 2rem;
margin: 5rem auto;
border-radius: 30px/15px;
border: dashed 2px var(--xata-accent);
font-size: 1.2rem;
text-align: center;
line-height: 2;
}
button {
background-color: transparent;
padding: 1rem 2rem;
border: solid 2px var(--xata-accent);
color: var(--xata-accent);
font-size: 2rem;
border-radius: 15px;
transition: all var(--transition-duration) ease-in-out;
display: block;
cursor: pointer;
}
button:hover,
button:focus {
border-color: transparent;
color: var(--background-color);
background-color: var(--xata-accent);
}
li button {
position: absolute;
padding: 1rem 2rem;
top: 0;
right: 0;
font-size: 1.2rem;
color: transparent;
text-shadow: 0 0 0 var(--text-color);
border: none;
}
li button:hover,
li button:focus {
text-shadow: 0 0 0 var(--xata-accent);
color: transparent;
background-color: transparent;
}
ul {
max-width: 120ch;
margin: 0 auto;
padding: 5rem 2rem;
display: grid;
grid-gap: 2rem;
list-style: none;
}
li {
position: relative;
padding: 1rem 2rem;
border: solid 2px var(--text-color);
border-radius: 10px/5px;
}
object {
position: relative;
top: 10px;
width: 2rem;
margin-left: 0.5em;
}
@media (min-width: 700px) {
ul {
grid-template-columns: 1fr 1fr;
}
}
@media (prefers-color-scheme: light) {
html {
--background-color: #fff;
--text-color: #000;
}
@media (prefers-reduced-motion) {
html {
--transition-duration: 0;
}
}
}
{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": false,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"incremental": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"composite": true
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
"exclude": ["node_modules"]
}
import {
BaseClientOptions,
buildClient,
SchemaInference,
XataRecord,
} from '@xata.io/client'
const tables = [
{
name: 'nextjs_with_xata_example',
columns: [
{ name: 'title', type: 'string' },
{ name: 'description', type: 'string' },
{ name: 'url', type: 'string' },
],
},
] as const
export type SchemaTables = typeof tables
export type DatabaseSchema = SchemaInference<SchemaTables>
export type NextjsWithXataExample = DatabaseSchema['nextjs_with_xata_example']
export type NextjsWithXataExampleRecord = NextjsWithXataExample & XataRecord
const DatabaseClient = buildClient()
const defaultOptions = {
databaseURL: 'https://xata-uq2d57.xata.sh/db/examples',
}
export class XataClient extends DatabaseClient<SchemaTables> {
constructor(options?: BaseClientOptions) {
super({ ...defaultOptions, ...options }, tables)
}
}
let instance: XataClient | undefined = undefined
export const getXataClient = () => {
if (instance) return instance
instance = new XataClient()
return instance
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment