Unverified Commit 0c6ee2c7 authored by Allen Hai's avatar Allen Hai Committed by GitHub

Add userbase example (#12150)

* add userbase example

* update readme and add now.json with build.env

* update deploy button import path for testing

* update readme

* update readme with canary tree path for deploy button

* remove prepopulated test username + password

* Apply lint-fix

* add deployed demo link

* remove merge conflict arrows

* fix lint errors

* run yarn lint-fix

* add .env.example and update readme with config steps

* add dotenv and update next.config.js
Co-authored-by: 's avatarMatthew Sweeney <mail@msweeneydev.com>
Co-authored-by: 's avatarJJ Kasper <jj@jjsweb.site>
parent 2ad35151
---
name: Bug report
about: Create a bug report for the Next.js core / examples
---
# Bug report
## Describe the bug
A clear and concise description of what the bug is.
## To Reproduce
Steps to reproduce the behavior, please provide code snippets or a repository:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
## Expected behavior
A clear and concise description of what you expected to happen.
## Screenshots
If applicable, add screenshots to help explain your problem.
## System information
- OS: [e.g. macOS, Windows]
- Browser (if applies) [e.g. chrome, safari]
- Version of Next.js: [e.g. 6.0.2]
- Version of Node.js: [e.g. 10.10.0]
## Additional context
Add any other context about the problem here.
---
name: Bug report
about: Create a bug report for the Next.js core / examples
---
# Bug report
## Describe the bug
A clear and concise description of what the bug is.
## To Reproduce
Steps to reproduce the behavior, please provide code snippets or a repository:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
## Expected behavior
A clear and concise description of what you expected to happen.
## Screenshots
If applicable, add screenshots to help explain your problem.
## System information
- OS: [e.g. macOS, Windows]
- Browser (if applies) [e.g. chrome, safari]
- Version of Next.js: [e.g. 6.0.2]
- Version of Node.js: [e.g. 10.10.0]
## Additional context
Add any other context about the problem here.
---
name: Feature request
about: Create a feature request for the Next.js core
---
# Feature request
## Is your feature request related to a problem? Please describe.
A clear and concise description of what you want and what your use case is.
## Describe the solution you'd like
A clear and concise description of what you want to happen.
## Describe alternatives you've considered
A clear and concise description of any alternative solutions or features you've considered.
## Additional context
Add any other context or screenshots about the feature request here.
---
name: Feature request
about: Create a feature request for the Next.js core
---
# Feature request
## Is your feature request related to a problem? Please describe.
A clear and concise description of what you want and what your use case is.
## Describe the solution you'd like
A clear and concise description of what you want to happen.
## Describe alternatives you've considered
A clear and concise description of any alternative solutions or features you've considered.
## Additional context
Add any other context or screenshots about the feature request here.
# Example App with next-less
This example demonstrates how to use the [next-less plugin](https://github.com/zeit/next-plugins/tree/master/packages/next-less).
It includes patterns for with and without CSS Modules, with PostCSS and with additional webpack configurations on top of the next-less plugin.
## Deploy your own
Deploy the example using [Vercel](https://vercel.com):
[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/import/project?template=https://github.com/zeit/next.js/tree/canary/examples/with-next-less)
## How to use
### Using `create-next-app`
Execute [`create-next-app`](https://github.com/zeit/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
npm init next-app --example with-next-less with-next-less-app
# or
yarn create next-app --example with-next-less with-next-less-app
```
### Download manually
Download the example:
```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/with-next-less
cd with-next-less
```
Install it and run:
```bash
npm install
npm run dev
# or
yarn
yarn dev
```
Deploy it to the cloud with [Vercel](https://vercel.com/import?filter=next.js&utm_source=github&utm_medium=readme&utm_campaign=next-example) ([Documentation](https://nextjs.org/docs/deployment)).
# Example App with next-less
This example demonstrates how to use the [next-less plugin](https://github.com/zeit/next-plugins/tree/master/packages/next-less).
It includes patterns for with and without CSS Modules, with PostCSS and with additional webpack configurations on top of the next-less plugin.
## Deploy your own
Deploy the example using [Vercel](https://vercel.com):
[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/import/project?template=https://github.com/zeit/next.js/tree/canary/examples/with-next-less)
## How to use
### Using `create-next-app`
Execute [`create-next-app`](https://github.com/zeit/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
npm init next-app --example with-next-less with-next-less-app
# or
yarn create next-app --example with-next-less with-next-less-app
```
### Download manually
Download the example:
```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/with-next-less
cd with-next-less
```
Install it and run:
```bash
npm install
npm run dev
# or
yarn
yarn dev
```
Deploy it to the cloud with [Vercel](https://vercel.com/import?filter=next.js&utm_source=github&utm_medium=readme&utm_campaign=next-example) ([Documentation](https://nextjs.org/docs/deployment)).
const withLess = require('@zeit/next-less')
/* Without CSS Modules, with PostCSS */
module.exports = withLess()
/* With CSS Modules */
// module.exports = withLess({ cssModules: true })
/* With additional configuration on top of CSS Modules */
/*
module.exports = withLess({
cssModules: true,
webpack: function (config) {
return config;
}
});
*/
const withLess = require('@zeit/next-less')
/* Without CSS Modules, with PostCSS */
module.exports = withLess()
/* With CSS Modules */
// module.exports = withLess({ cssModules: true })
/* With additional configuration on top of CSS Modules */
/*
module.exports = withLess({
cssModules: true,
webpack: function (config) {
return config;
}
});
*/
/*
In production the stylesheet is compiled to .next/static/style.css and served from /_next/static/style.css
You have to include it into the page using either next/head or a custom _document.js, as is being done in this file.
*/
import Document, { Head, Main, NextScript } from 'next/document'
export default class MyDocument extends Document {
render() {
return (
<html>
<Head />
<body>
<Main />
<NextScript />
</body>
</html>
)
}
}
/*
In production the stylesheet is compiled to .next/static/style.css and served from /_next/static/style.css
You have to include it into the page using either next/head or a custom _document.js, as is being done in this file.
*/
import Document, { Head, Main, NextScript } from 'next/document'
export default class MyDocument extends Document {
render() {
return (
<html>
<Head />
<body>
<Main />
<NextScript />
</body>
</html>
)
}
}
// Without CSS Modules
import '../style.less'
export default () => <div className="example">Hello Less!</div>
// With CSS Modules
/*
import style from '../style.less'
export default () => <div className={style.example}>Hello Less!</div>
*/
// Without CSS Modules
import '../style.less'
export default () => <div className="example">Hello Less!</div>
// With CSS Modules
/*
import style from '../style.less'
export default () => <div className={style.example}>Hello Less!</div>
*/
USERBASE_APP_ID=<place-your-id-here>
\ No newline at end of file
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# local env files
.env
.env.local
.env.development.local
.env.test.local
.env.production.local
# vercel
.now
\ No newline at end of file
# Userbase Example
This is an example of using [Userbase](https://userbase.com) in a Next.js project.
Deployed Demo: [https://next-userbase.now.sh](https://next-userbase.now.sh)
## Deploy your own
Deploy the example using [Vercel](https://vercel.com):
[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/import/project?template=https://github.com/zeit/next.js/tree/canary/examples/with-userbase)
## How to use
### Using `create-next-app`
Execute [`create-next-app`](https://github.com/zeit/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
npm init next-app --example with-userbase next-userbase-app
# or
yarn create next-app --example with-userbase next-userbase-app
```
### Download manually
Download the example:
```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/with-userbase
cd with-userbase
```
Install it and run:
```bash
npm install
npm run dev
# or
yarn
yarn dev
```
## Configuration
### Step 1. Create an account on Userbase
First, [create an account on Userbase](https://userbase.com).
After creating an account, make note of your _App ID_ which you'll be needing later.
### Step 2. Setting up environment variables
Copy the `.env.example` file in this directory to `.env` (which will be ignored by Git):
```bash
cp .env.example .env
```
Then set the variable on `.env`:
- `USERBASE_APP_ID` should be the _App ID_ from when you created your Userbase account.
Your `.env` file should look like this:
```bash
USERBASE_APP_ID=...
```
### Step 3. Run Next.js in development mode
```bash
npm install
npm run dev
# or
yarn install
yarn dev
```
Your todo app should be up and running on [http://localhost:3000](http://localhost:3000)! If it doesn't work, post on [GitHub discussions](https://github.com/zeit/next.js/discussions).
### Step 4. Deploy on Vercel
You can deploy this app to the cloud with [Vercel](https://vercel.com/import?filter=next.js&utm_source=github&utm_medium=readme&utm_campaign=next-example) ([Documentation](https://nextjs.org/docs/deployment)).
To deploy on Vercel, you need to set the environment variables with **Now Secrets** using [Now CLI](https://vercel.com/download) ([Documentation](https://vercel.com/docs/now-cli#commands/secrets)).
Install [Now CLI](https://vercel.com/download), log in to your account from the CLI, and run the following commands to add the environment variables. Replace `<NEXT_EXAMPLE_CMS_DATOCMS_API_TOKEN>` and `<NEXT_EXAMPLE_CMS_DATOCMS_PREVIEW_SECRET>` with the corresponding strings in `.env`.
```
now secrets add userbase-app-id <USERBASE_APP_ID>
```
Then push the project to GitHub/GitLab/Bitbucket and [import to Vercel](https://vercel.com/import?filter=next.js&utm_source=github&utm_medium=readme&utm_campaign=next-example) to deploy.
import Nav from '../nav'
function Layout({ user, setUser, children }) {
return (
<div className="container mx-auto">
<Nav user={user} setUser={setUser} />
{children}
</div>
)
}
export default Layout
import { useState, useEffect } from 'react'
import userbase from 'userbase-js'
function LoginModal({ toggle, modalType, setUser }) {
const [username, setUsername] = useState('')
const [password, setPassword] = useState('')
const [loading, setLoading] = useState()
const [error, setError] = useState()
useEffect(() => {
setError('')
}, [modalType])
async function handleSignUp(e) {
e.preventDefault()
setLoading(true)
try {
const user = await userbase.signUp({
username,
password,
rememberMe: 'none',
})
setUser(user)
setLoading(false)
toggle(false)
} catch (e) {
setLoading(false)
setError(e.message)
}
}
async function handleLogIn(e) {
e.preventDefault()
setLoading(true)
try {
const user = await userbase.signIn({
username,
password,
rememberMe: 'none',
})
setUser(user)
setLoading(false)
toggle(false)
} catch (e) {
setLoading(false)
setError(e.message)
}
}
return (
<form className="bg-white shadow-md rounded p-8">
<div className="mb-4">
<label
className="block text-purple-700 text-sm font-bold mb-2"
htmlFor="username"
>
Username
</label>
<input
className="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
id="username"
type="text"
placeholder="Username"
value={username}
onChange={e => setUsername(e.target.value)}
/>
</div>
<div className="mb-4">
<label
className="block text-purple-700 text-sm font-bold mb-2"
htmlFor="username"
>
Password
</label>
<input
className="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
id="password"
type="password"
placeholder="*******"
value={password}
onChange={e => setPassword(e.target.value)}
/>
</div>
<div className="flex items-center justify-between">
<span
className="font-bold cursor-pointer"
onClick={() => toggle(false)}
>
Cancel
</span>
{modalType === 'logIn' ? (
<button
disabled={loading}
className="btn-yellow"
onClick={handleLogIn}
>
{loading ? 'Logging In ...' : 'Log In'}
</button>
) : (
<button
disabled={loading}
className="btn-yellow"
onClick={handleSignUp}
>
{loading ? 'Signing up ...' : 'Sign Up'}
</button>
)}
</div>
<p className="text-red-500 font-bold">{error}</p>
</form>
)
}
export default LoginModal
import { useState } from 'react'
import LoginModal from '../modal'
import userbase from 'userbase-js'
export default function Nav({ user, setUser }) {
const [open, setOpen] = useState()
const [modalType, setModalType] = useState()
function openModal(type) {
setOpen(true)
setModalType(type)
}
async function logOut() {
try {
await userbase.signOut()
setUser(null)
} catch (e) {
console.error(e.message)
}
}
return (
<nav className="container mx-auto">
<ul className="flex justify-end items-center p-8">
{!user ? (
<>
<li>
<button
className="font-bold mx-2"
onClick={() => openModal('logIn')}
>
Log In
</button>
</li>
<li>
<button
className="btn-yellow mx-2"
onClick={() => openModal('signUp')}
>
Sign Up
</button>
</li>
</>
) : (
<li>
<button className="font-bold" onClick={logOut}>
Log Out
</button>
</li>
)}
</ul>
{open && (
<div className="w-4/5 md:w-1/2 mx-auto">
<LoginModal
toggle={setOpen}
modalType={modalType}
setUser={setUser}
/>
</div>
)}
</nav>
)
}
import { useState, useEffect } from 'react'
import userbase from 'userbase-js'
function Todo({ name, done, toggleComplete, deleteTodo }) {
return (
<li className="my-4">
<div className="flex items-center">
<span className={done ? 'text-gray-500' : ''}>{name}</span>
<button
type="button"
className="mx-4 p-1 rounded bg-purple-400 text-white font-bold"
onClick={e => {
e.preventDefault()
toggleComplete()
}}
>
{done ? 'not done' : 'done'}
</button>
<button
type="button"
onClick={e => {
e.preventDefault()
deleteTodo()
}}
className=" p-1 bg-red-500 text-white rounded font-bold"
>
delete
</button>
</div>
</li>
)
}
function TodoForm() {
const [newTodo, setNewTodo] = useState('')
const [todos, setTodos] = useState([])
const [disabled, setDisabled] = useState()
useEffect(() => {
async function openDatabase() {
try {
console.log('opening db...')
await userbase.openDatabase({
databaseName: 'next-userbase-todos',
changeHandler: function(items) {
setTodos(items)
},
})
} catch (e) {
console.error(e.message)
}
}
openDatabase()
}, [])
async function addTodo(e) {
e.preventDefault()
setDisabled(true)
try {
await userbase.insertItem({
databaseName: 'next-userbase-todos',
item: { name: newTodo, done: false },
})
setNewTodo('')
setDisabled(false)
} catch (e) {
console.error(e.message)
setDisabled(false)
}
}
async function toggleComplete(itemId, currentValue) {
try {
await userbase.updateItem({
databaseName: 'next-userbase-todos',
item: { ...currentValue, done: !currentValue.done },
itemId,
})
} catch (e) {
console.error(e.message)
}
}
function handleNewTodo(e) {
e.preventDefault()
setNewTodo(e.target.value)
}
async function deleteTodo(itemId) {
setDisabled(true)
try {
await userbase.deleteItem({
databaseName: 'next-userbase-todos',
itemId,
})
setNewTodo('')
setDisabled(false)
} catch (e) {
console.error(e.message)
setDisabled(false)
}
}
return (
<form className="bg-white shadow-md rounded p-8" onSubmit={addTodo}>
<ul>
{todos.map(todo => (
<Todo
key={todo.itemId}
name={todo.item.name}
done={todo.item.done}
toggleComplete={() => toggleComplete(todo.itemId, todo.item)}
deleteTodo={() => deleteTodo(todo.itemId)}
/>
))}
</ul>
<div className="flex my-4">
<input
type="text"
onChange={handleNewTodo}
value={newTodo}
className="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
/>
<button disabled={disabled} className="btn-yellow mx-4" type="submit">
add
</button>
</div>
</form>
)
}
export default TodoForm
require('dotenv').config()
module.exports = {
env: {
USERBASE_APP_ID: process.env.USERBASE_APP_ID,
},
}
{
"build": {
"env": {
"USERBASE_APP_ID": "@userbase-app-id"
}
}
}
{
"name": "with-tailwindcss",
"version": "1.0.0",
"scripts": {
"dev": "next",
"build": "next build",
"start": "next start"
},
"dependencies": {
"dotenv": "8.2.0",
"next": "^9.2.0",
"react": "^16.12.0",
"react-dom": "^16.12.0",
"userbase-js": "^1.3.0"
},
"devDependencies": {
"@fullhuman/postcss-purgecss": "^1.3.0",
"postcss-preset-env": "^6.7.0",
"tailwindcss": "^1.1.4"
}
}
import { useState, useEffect } from 'react'
import userbase from 'userbase-js'
import Layout from '../components/layout'
import '../styles/index.css'
function MyApp({ Component, pageProps }) {
const [user, setUser] = useState()
useEffect(() => {
userbase.init({ appId: process.env.USERBASE_APP_ID })
}, [])
return (
<Layout user={user} setUser={setUser}>
<Component user={user} {...pageProps} />
</Layout>
)
}
export default MyApp
import TodoForm from '../components/todo-form'
function Index({ user }) {
if (user) {
return (
<div className="w-4/5 md:w-1/2 mx-auto">
<h3 className="font-bold text-4xl">
Welcome, <span className="bg-yellow-400">{user.username}</span>!
</h3>
<TodoForm />
</div>
)
} else {
return null
}
}
export default Index
module.exports = {
plugins: [
'tailwindcss',
...(process.env.NODE_ENV === 'production'
? [
[
'@fullhuman/postcss-purgecss',
{
content: [
'./pages/**/*.{js,jsx,ts,tsx}',
'./components/**/*.{js,jsx,ts,tsx}',
],
defaultExtractor: content =>
content.match(/[\w-/:]+(?<!:)/g) || [],
},
],
]
: []),
'postcss-preset-env',
],
}
.btn-yellow {
@apply bg-yellow-400 text-black font-bold py-2 px-4 rounded;
}
.btn-yellow:hover {
@apply bg-yellow-500;
}
@import './button.css';
/* purgecss start ignore */
@tailwind base;
@tailwind components;
/* purgecss end ignore */
@tailwind utilities;
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