Unverified Commit c81eadc6 authored by Noah Fischer's avatar Noah Fischer Committed by GitHub

moving to upstash and new integration (#22436)

parent a0d44ca3
# Redis Example
# Redis Example (with Upstash)
This example showcases how to use Redis as a data store in a Next.js project. [Lambda Store](https://lambda.store/) is used as managed Redis service.
This example showcases how to use Redis as a data store in a Next.js project.
The example is a basic roadmap voting application where users can enter and vote for feature requests. It features the following:
The example is a roadmap voting application where users can enter and vote for feature requests. It features the
following:
- Users can add and upvote items (features in the roadmap), and enter their email addresses to be notified about the released items.
- The API records the ip-addresses of the voters, so it does not allow multiple votes on the same item from the same IP address.
- To find the id of any item, click the vote button, you will see its id on the url.
- Users can add and upvote items (features in the roadmap), and enter their email addresses to be notified about the
released items.
- The API records the ip-addresses of the voters, so it does not allow multiple votes on the same item from the same IP
address.
## Demo
[https://roadmap-voting-demo.vercel.app/](https://roadmap-voting-demo.vercel.app/)
See
[https://roadmap.upstash.com](https://roadmap.upstash.com)
## Deploy your own
## Deploy Your Own
Once you have access to [the environment variables you'll need](#configuration), deploy the example using [Vercel](https://vercel.com?utm_source=github&utm_medium=readme&utm_campaign=next-example):
You can deploy Roadmap Voting App for your project/company
using [Vercel and Upstash](https://vercel.com/integrations/upstash) clicking the below button:
[![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-redis&project-name=with-redis&repository-name=with-redis&env=REDIS_URL&envDescription=Required%20to%20connect%20the%20app%20to%20Redis&envLink=https://github.com/vercel/next.js/tree/canary/examples/with-redis%23configuration)
## 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) or [Yarn](https://yarnpkg.com/lang/en/docs/cli/create/) to bootstrap the example:
```bash
npx create-next-app --example with-redis with-redis-app
# or
yarn create next-app --example with-redis with-redis-app
```
[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/git/external?repository-url=https%3A%2F%2Fgithub.com%2Fupstash%2Fserverless-tutorials%2Ftree%2Fmaster%2Froadmap-voting-app&env=LOGO&envDescription=Enter%20URL%20for%20your%20project%2Fcompany%20logo&envLink=https%3A%2F%2Fdocs.upstash.com%2Fdocs%2Ftutorials%2Froadmap_voting_app&project-name=roadmap-voting&repo-name=roadmap-voting&demo-title=Roadmap%20Voting&demo-description=Roadmap%20Voting%20Page%20for%20Your%20Project&demo-url=https%3A%2F%2Froadmap.upstash.com&integration-ids=oac_V3R1GIpkoJorr6fqyiwdhl17)
## Configuration
A data store with Redis is required for the app to work. In the steps below we'll integrate Lambda Store as the data store.
### Without Vercel
If you are planning to deploy your application to somewhere other than Vercel, you'll need to integrate Lambda Store by setting an environment variable.
First, create an account and a database in the [Lambda Store console](https://console.lambda.store/).
To connect to Redis, you will need your Redis connection string. You can get the connection string by clicking on **Connect** in the Database page within the Lambda Store dashboard as below:
![setup without vercel](./docs/lstr6.png)
Next, create a file called `.env.local` in the root directory and copy your connection string:
```bash
REDIS_URL="YOUR_REDIS_CONNECTION_STRING"
REDIS_PASSWORD="YOUR_REDIS_CONNECTION_PASSWORD"
```
Your app is now connected to a remote Redis database!
### Using Vercel
You can add the Lambda Store integration to your Vercel account. Once you set up the integration you won't have to visit the Lambda Store console anymore. Follow the next steps to setup the integration:
#### Step 1. Deploy Your Local Project
To deploy your local project to Vercel, push it to GitHub/GitLab/Bitbucket and [import to Vercel](https://vercel.com/new?utm_source=github&utm_medium=readme&utm_campaign=next-example).
#### Step 2. Add the Lambda Store Integration to Your Vercel Account
Visit Vercel [Lambda Store Integration](https://vercel.com/integrations/lambdastore) page and click the `Add` button.
The application uses [Upstash](https://upstash.com) (Serverless Redis Database) as its data storage. During deployment,
you will be asked to integrate Upstash. The integration dialog will help you create an Upstash database for free and
link it to your Vercel project with the following steps:
#### Step 3. Configure the Integration
### Deployment Steps
The integration requires a [Developer API Key](howto/developerapi.md) that can be created from the [Lambda Store console](https://console.lambda.store).
After clicking the deploy button, enter a name for your project. Then you will be asked to install Upstash integration.
<br/>
<img src="./docs/s2.png" width="300" />
<br/>
Enter the API key and your registered email address in the integration setup page:
You can sign up/sign in the following dialog:
![setup](./docs/lstr1.png)
<img src="./docs/s3.png" width="300" />
#### Step 4. Create a Database
Create a free database:
In the next page of the integration setup, your databases will be automatically listed. A new database can be created from the Vercel Integration page as well as in the Lambda Store Console:
<img src="./docs/s4.png" width="300" />
![new db](./docs/lstr2.png)
Select your database and the Vercel project:
Click the **New Database**, you should be able to see the page below:
<img src="./docs/s5.png" width="300" />
![new db form](./docs/lstr3.png)
Click `COMPLETE ON VERCEL` button:
Fill out the form and click on **Create** to have your new database.
<img src="./docs/s6.png" width="300" />
#### Step 5. Link the Database to Your Project
Finish you deployment by choosing a repository to host the project. In the next step, set the URL of your project's
logo:
Select your project from the dropdown menu then click on **Link To Project** for any database.
<img src="./docs/s7.png" width="300" />
`REDIS_URL` will be automatically set as an environment variable for your application.
Your Roadmap Voting Page should be ready:
![link project](./docs/lstr4.png)
<img src="./docs/s8.png" width="300" />
![redis url env](./docs/lstr5.png)
### Maintenance
**Important:** You will need to re-deploy your application for the change to be effective.
The application uses a Redis database to store the feature requests and emails. The features requests are kept in a
sorted set with name `roadmap`. You can connect to it via Redis-cli and manage the data using the
command `zrange roadmap 0 1000 WITHSCORES`. The emails are stored in a set with name `emails`. So you can get the list
by the command `smembers emails`.
{
"name": "with-redis",
"version": "0.1.0",
"version": "0.1.1",
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start"
},
"dependencies": {
"ioredis": "^4.22.0",
"next": "latest",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"react-toastify": "^6.0.8",
"redis": "^3.0.2",
"uuid": "^8.2.0"
"react": "17.0.1",
"react-dom": "17.0.1",
"react-toastify": "^6.0.8"
},
"license": "MIT"
"devDependencies": {
"prettier": "^2.2.1"
}
}
import './index.css'
import 'react-toastify/dist/ReactToastify.css'
import '../styles/base.css'
// This default export is required in a new `pages/_app.js` file.
export default function MyApp({ Component, pageProps }) {
......
import redis from 'redis'
import { promisify } from 'util'
import { getRedis } from './utils'
export default async function addEmail(req, res) {
const client = redis.createClient({
url: process.env.REDIS_URL,
})
if (process.env.REDIS_PASSWORD) {
client.auth(process.env.REDIS_PASSWORD)
}
const saddAsync = promisify(client.sadd).bind(client)
module.exports = async (req, res) => {
let redis = getRedis()
const body = req.body
const email = body['email']
client.on('error', function (err) {
redis.on('error', function (err) {
throw err
})
if (email && validateEmail(email)) {
await saddAsync('emails', email)
client.quit()
await redis.sadd('emails', email)
redis.quit()
res.json({
body: 'success',
})
} else {
client.quit()
redis.quit()
res.json({
error: 'Invalid email',
})
......
import redis from 'redis'
import { promisify } from 'util'
import { v4 as uuidv4 } from 'uuid'
export default async function create(req, res) {
const client = redis.createClient({
url: process.env.REDIS_URL,
})
if (process.env.REDIS_PASSWORD) {
client.auth(process.env.REDIS_PASSWORD)
}
const hsetAsync = promisify(client.hset).bind(client)
const zaddAsync = promisify(client.zadd).bind(client)
import { getRedis } from './utils'
module.exports = async (req, res) => {
let redis = getRedis()
const body = req.body
const title = body['title']
const id = uuidv4()
client.on('error', function (err) {
throw err
})
if (title) {
await zaddAsync('roadmap', 0, id)
await hsetAsync(id, 'title', title)
client.quit()
if (!title) {
redis.quit()
res.json({
error: 'Feature can not be empty',
})
} else if (title.length < 70) {
await redis.zadd('roadmap', 'NX', 1, title)
redis.quit()
res.json({
body: 'success',
})
} else {
client.quit()
redis.quit()
res.json({
error: 'Feature can not be empty',
error: 'Max 70 characters please.',
})
}
}
import redis from 'redis'
import { promisify } from 'util'
import { getRedis } from './utils'
export default async function list(req, res) {
const client = redis.createClient({
url: process.env.REDIS_URL,
})
if (process.env.REDIS_PASSWORD) {
client.auth(process.env.REDIS_PASSWORD)
}
const hgetallAsync = promisify(client.hgetall).bind(client)
const zrevrangeAsync = promisify(client.zrevrange).bind(client)
let n = await zrevrangeAsync('roadmap', 0, 50, 'WITHSCORES')
module.exports = async (req, res) => {
let redis = getRedis()
let n = await redis.zrevrange('roadmap', 0, 100, 'WITHSCORES')
let result = []
const promises = []
for (let i = 0; i < n.length - 1; i += 2) {
let id = n[i]
let p = hgetallAsync(id).then((item) => {
if (item) {
item['id'] = id
item['score'] = n[i + 1]
result.push(item)
}
})
promises.push(p)
let item = {}
item['title'] = n[i]
item['score'] = n[i + 1]
result.push(item)
}
await Promise.all(promises).then(() => {
client.quit()
})
redis.quit()
res.json({
body: result,
......
import Redis from 'ioredis'
function fixUrl(url) {
if (!url) {
return ''
}
if (url.startsWith('redis://') && !url.startsWith('redis://:')) {
return url.replace('redis://', 'redis://:')
}
if (url.startsWith('rediss://') && !url.startsWith('rediss://:')) {
return url.replace('rediss://', 'rediss://:')
}
return url
}
export function getRedis() {
return new Redis(fixUrl(process.env.REDIS_URL))
}
import redis from 'redis'
import { promisify } from 'util'
export default async function list(req, res) {
const client = redis.createClient({
url: process.env.REDIS_URL,
})
if (process.env.REDIS_PASSWORD) {
client.auth(process.env.REDIS_PASSWORD)
}
client.on('error', function (err) {
throw err
})
import { getRedis } from './utils'
module.exports = async (req, res) => {
let redis = getRedis()
const body = req.body
const id = body['id']
let ip = req.headers['x-forwarded-for']
const saddAsync = promisify(client.sadd).bind(client)
let c = await saddAsync('s:' + id, ip ? ip : '-')
const title = body['title']
let ip = req.headers['x-forwarded-for'] || req.headers['Remote_Addr'] || 'NA'
let c = ip === 'NA' ? 1 : await redis.sadd('s:' + title, ip)
if (c === 0) {
client.quit()
redis.quit()
res.json({
error: 'You can not vote an item multiple times',
})
} else {
const zincrbyAsync = promisify(client.zincrby).bind(client)
let v = await zincrbyAsync('roadmap', 1, id)
client.quit()
let v = await redis.zincrby('roadmap', 1, title)
redis.quit()
res.json({
body: v,
})
......
......@@ -40,7 +40,7 @@ footer {
footer img {
margin-left: 0.5rem;
margin-right: 0.5rem;
height: 1em;
height: 1.5em;
}
footer a {
......
import Head from 'next/head'
import { ToastContainer, toast } from 'react-toastify'
import React, { useState, useRef, useEffect } from 'react'
import React, { useState, useEffect, useRef } from 'react'
function Home() {
const [items, setItems] = useState(0)
const inputNewFeature = useRef()
const inputEmail = useRef()
const logo = process.env.LOGO ? process.env.LOGO : '/logo.png'
const [loaded, setLoaded] = useState(false)
const [items, setItems] = useState([])
useEffect(() => {
refreshData()
}, [])
function refreshData() {
const refreshData = () => {
fetch('api/list')
.then((res) => res.json())
.then(
(result) => {
setItems(result.body)
setLoaded(true)
inputNewFeature.current.value = ''
inputEmail.current.value = ''
},
(error) => {
setItems([])
console.log(error)
setLoaded(true)
}
)
}
function handleNewFeature(event) {
const vote = (event, title) => {
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title: inputNewFeature.current.value }),
body: JSON.stringify({ title: title }),
}
fetch('api/create', requestOptions)
fetch('api/vote', requestOptions)
.then((response) => response.json())
.then((data) => {
if (data.error) {
toast.error(data.error, { hideProgressBar: true, autoClose: 3000 })
} else {
toast.info('Your feature has been added to the list.', {
hideProgressBar: true,
autoClose: 3000,
})
refreshData()
}
})
event.preventDefault()
}
function handleNewEmail(event) {
const handleNewFeature = (event) => {
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email: inputEmail.current.value }),
body: JSON.stringify({ title: inputNewFeature.current.value }),
}
console.log(requestOptions)
fetch('api/addemail', requestOptions)
fetch('api/create', requestOptions)
.then((response) => response.json())
.then((data) => {
if (data.error) {
toast.error(data.error, { hideProgressBar: true, autoClose: 3000 })
toast.error(data.error, { hideProgressBar: true, autoClose: 5000 })
} else {
toast.info('Your email has been added to the list.', {
toast.info('Your feature has been added to the list.', {
hideProgressBar: true,
autoClose: 3000,
})
......@@ -71,23 +68,27 @@ function Home() {
event.preventDefault()
}
function vote(event, id) {
const handleNewEmail = (event) => {
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ id: id }),
body: JSON.stringify({ email: inputEmail.current.value }),
}
console.log(requestOptions)
fetch('api/vote', requestOptions)
fetch('api/addemail', requestOptions)
.then((response) => response.json())
.then((data) => {
console.log(data)
if (data.error) {
toast.error(data.error, { hideProgressBar: true, autoClose: 3000 })
} else {
toast.info('Your email has been added to the list.', {
hideProgressBar: true,
autoClose: 3000,
})
inputEmail.current.value = ''
refreshData()
}
})
event.preventDefault()
}
return (
......@@ -99,31 +100,39 @@ function Home() {
<main>
<h1 className="title">
<img src="/logo.png" alt="Your Project Logo" className="logo" />
<img src={logo} alt="Logo" className="logo" />
</h1>
<p className="description">
Help us by voting our roadmap. <br />
Help us by voting our roadmap.
<br />
<span className="blue">&#x25B2;</span>
Vote up the features you want to see in the next release.
</p>
<div className="grid">
{items
? items.map((item, ind) => (
<div className="card" key={ind}>
<span>{item.title}</span>
<div className="upvotediv">
<a onClick={(e) => vote(e, item.id)} href={'#' + item.id}>
&#x25B2; {item.score}
</a>
</div>
{loaded ? (
items.map((item, ind) => (
<div className="card" key={ind}>
<span>{item.title}</span>
<div className="upvotediv">
<a
onClick={(e) => vote(e, item.title)}
href={'#' + item.title}
>
&#x25B2; {item.score}
</a>
</div>
))
: ''}
</div>
))
) : (
<div className="card">
<img src="/loader.gif" />
</div>
)}
<div className="card">
<form onSubmit={(e) => handleNewFeature(e)}>
<form onSubmit={handleNewFeature}>
<input
type="text"
className="noborder"
......@@ -135,7 +144,7 @@ function Home() {
</div>
<div className="card">
<form onSubmit={(e) => handleNewEmail(e)}>
<form onSubmit={handleNewEmail}>
<input
type="text"
className="noborder"
......@@ -150,14 +159,14 @@ function Home() {
<footer>
<a
href="http://github.com/vercel/next.js/tree/canary/examples/with-redis"
href="https://vercel.com/integrations/upstash"
target="_blank"
rel="noopener noreferrer"
>
Powered by
<img src="/vercel.svg" alt="Vercel Logo" />
and
<img src="/lstr.png" alt="Lambda Store Logo" />
<img src="/upstash.png" alt="Upstash Logo" />
</a>
</footer>
<ToastContainer />
......
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