Skip to content
This repository was archived by the owner on Feb 7, 2025. It is now read-only.

Commit 5f16248

Browse files
author
Maricris Bonzo
committed
Create client side locally
0 parents  commit 5f16248

19 files changed

+5192
-0
lines changed

.env.local.example

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
NEXT_PUBLIC_MAGIC_PUBLISHABLE_KEY=
2+
MAGIC_SECRET_KEY=
3+
TOKEN_SECRET="this-is-a-secret-value-with-at-least-32-characters"

.gitignore

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
2+
3+
# dependencies
4+
/node_modules
5+
/.pnp
6+
.pnp.js
7+
8+
# testing
9+
/coverage
10+
11+
# next.js
12+
/.next/
13+
/out/
14+
15+
# production
16+
/build
17+
18+
# misc
19+
.DS_Store
20+
*.pem
21+
22+
# debug
23+
npm-debug.log*
24+
yarn-debug.log*
25+
yarn-error.log*
26+
27+
# local env files
28+
.env.local
29+
.env.development.local
30+
.env.test.local
31+
.env.production.local
32+
33+
# vercel
34+
.vercel

README.md

+69
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
# Magic Example
2+
3+
This example shows how to use [Magic](https://magic.link) with Next.js. The example features cookie-based, passwordless authentication with email-based magic links.
4+
5+
The example shows how to do a login and logout; and to get the user info using a hook with [SWR](https://swr.now.sh).
6+
7+
A DB is not included. But you can add any DB you like!.
8+
9+
The login cookie is `httpOnly`, meaning it can only be accessed by the API, and it's encrypted using [@hapi/iron](https://hapi.dev/family/iron) for more security.
10+
11+
## Deploy your own
12+
13+
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):
14+
15+
[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/import/git?c=1&s=https://github.com/vercel/next.js/tree/canary/examples/with-magic&env=NEXT_PUBLIC_MAGIC_PUBLISHABLE_KEY,MAGIC_SECRET_KEY,TOKEN_SECRET&envDescription=Required%20to%20connect%20the%20app%20with%20Magic&envLink=https://github.com/vercel/next.js/tree/canary/examples/with-magic%23configuration)
16+
17+
## How to use
18+
19+
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:
20+
21+
```bash
22+
npx create-next-app --example with-magic with-magic-app
23+
# or
24+
yarn create next-app --example with-magic with-magic-app
25+
```
26+
27+
## Configuration
28+
29+
Login to the [Magic Dashboard](https://dashboard.magic.link/) and get the keys of your application
30+
31+
![Magic Dashboard](https://gblobscdn.gitbook.com/assets%2F-M1XNjqusnKyXZc7t7qQ%2F-M3HsSftOAghkNs-ttU3%2F-M3HsllfdwdDmeFXBK3U%2Fdashboard-pk.png?alt=media&token=4d6e7543-ae20-4355-951c-c6421b8f1b5f)
32+
33+
Next, copy the `.env.local.example` file in this directory to .env.local (which will be ignored by Git):
34+
35+
```bash
36+
cp .env.local.example .env.local
37+
```
38+
39+
Then set each variable on `.env.local`:
40+
41+
- `NEXT_PUBLIC_MAGIC_PUBLISHABLE_KEY` should look like `pk_test_abc` or `pk_live_ABC`
42+
- `MAGIC_SECRET_KEY` should look like `sk_test_ABC` or `sk_live_ABC`
43+
- `TOKEN_SECRET` should be a string with at least 32 characters
44+
45+
Now, run Next.js in development mode
46+
47+
```bash
48+
npm run dev
49+
# or
50+
yarn dev
51+
```
52+
53+
Your 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/vercel/next.js/discussions).
54+
55+
## Deploy on Vercel
56+
57+
You can deploy this app to the cloud with [Vercel](https://vercel.com?utm_source=github&utm_medium=readme&utm_campaign=next-example) ([Documentation](https://nextjs.org/docs/deployment)).
58+
59+
#### Deploy Your Local Project
60+
61+
To deploy your local project to Vercel, push it to GitHub/GitLab/Bitbucket and [import to Vercel](https://vercel.com/import/git?utm_source=github&utm_medium=readme&utm_campaign=next-example).
62+
63+
**Important**: When you import your project on Vercel, make sure to click on **Environment Variables** and set them to match your `.env.local` file.
64+
65+
#### Deploy from Our Template
66+
67+
Alternatively, you can deploy using our template by clicking on the Deploy button below.
68+
69+
[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/import/git?c=1&s=https://github.com/vercel/next.js/tree/canary/examples/with-magic&env=NEXT_PUBLIC_MAGIC_PUBLISHABLE_KEY,MAGIC_SECRET_KEY,TOKEN_SECRET&envDescription=Required%20to%20connect%20the%20app%20with%20Magic&envLink=https://github.com/vercel/next.js/tree/canary/examples/with-magic%23configuration)

components/form.js

+56
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
const Form = ({ errorMessage, onSubmit }) => (
2+
<form onSubmit={onSubmit}>
3+
<label>
4+
<span>Email</span>
5+
<input type="email" name="email" required />
6+
</label>
7+
8+
<div className="submit">
9+
<button type="submit">Sign Up / Login</button>
10+
</div>
11+
12+
{errorMessage && <p className="error">{errorMessage}</p>}
13+
14+
<style jsx>{`
15+
form,
16+
label {
17+
display: flex;
18+
flex-flow: column;
19+
}
20+
label > span {
21+
font-weight: 600;
22+
}
23+
input {
24+
padding: 8px;
25+
margin: 0.3rem 0 1rem;
26+
border: 1px solid #ccc;
27+
border-radius: 4px;
28+
}
29+
.submit {
30+
display: flex;
31+
justify-content: flex-end;
32+
align-items: center;
33+
justify-content: space-between;
34+
}
35+
.submit > a {
36+
text-decoration: none;
37+
}
38+
.submit > button {
39+
padding: 0.5rem 1rem;
40+
cursor: pointer;
41+
background: #fff;
42+
border: 1px solid #ccc;
43+
border-radius: 4px;
44+
}
45+
.submit > button:hover {
46+
border-color: #888;
47+
}
48+
.error {
49+
color: brown;
50+
margin: 1rem 0 0;
51+
}
52+
`}</style>
53+
</form>
54+
)
55+
56+
export default Form

components/header.js

+62
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
import Link from 'next/link'
2+
import { useUser } from '../lib/hooks'
3+
4+
const Header = () => {
5+
const user = useUser()
6+
7+
return (
8+
<header>
9+
<nav>
10+
<ul>
11+
<li>
12+
<Link href="/">
13+
<a>Home</a>
14+
</Link>
15+
</li>
16+
{user ? (
17+
<>
18+
<li>
19+
<a href="/api/logout">Logout</a>
20+
</li>
21+
</>
22+
) : (
23+
<li>
24+
<Link href="/login">
25+
<a>Login</a>
26+
</Link>
27+
</li>
28+
)}
29+
</ul>
30+
</nav>
31+
<style jsx>{`
32+
nav {
33+
max-width: 42rem;
34+
margin: 0 auto;
35+
padding: 0.2rem 1.25rem;
36+
}
37+
ul {
38+
display: flex;
39+
list-style: none;
40+
margin-left: 0;
41+
padding-left: 0;
42+
}
43+
li {
44+
margin-right: 1rem;
45+
}
46+
li:first-child {
47+
margin-left: auto;
48+
}
49+
a {
50+
color: #fff;
51+
text-decoration: none;
52+
}
53+
header {
54+
color: #fff;
55+
background-color: #333;
56+
}
57+
`}</style>
58+
</header>
59+
)
60+
}
61+
62+
export default Header

components/layout.js

+57
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
import Head from 'next/head'
2+
import Header from './header'
3+
4+
const Layout = (props) => (
5+
<>
6+
<Head>
7+
<title>✨ Secure Your Go Rest API with Magic Auth ✨</title>
8+
<link rel="icon" href="/favicon.ico" />
9+
</Head>
10+
11+
<Header />
12+
13+
<main>
14+
<div className="container">{props.children}</div>
15+
</main>
16+
17+
<footer>
18+
<a
19+
href="https://vercel.com?utm_source=create-next-app&utm_medium=default-template&utm_campaign=create-next-app"
20+
target="_blank"
21+
rel="noopener noreferrer"
22+
>
23+
Powered by <img src="/vercel.svg" alt="Vercel Logo" />
24+
</a>
25+
</footer>
26+
27+
<style jsx global>{`
28+
*,
29+
*::before,
30+
*::after {
31+
box-sizing: border-box;
32+
}
33+
body {
34+
margin: 0;
35+
color: #333;
36+
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto,
37+
'Helvetica Neue', Arial, Noto Sans, sans-serif, 'Apple Color Emoji',
38+
'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji';
39+
}
40+
.container {
41+
max-width: 42rem;
42+
margin: 0 auto;
43+
padding: 2rem 1.25rem;
44+
}
45+
footer {
46+
width: 100%;
47+
height: 100px;
48+
border-top: 1px solid #eaeaea;
49+
display: flex;
50+
justify-content: center;
51+
align-items: center;
52+
}
53+
`}</style>
54+
</>
55+
)
56+
57+
export default Layout

lib/auth-cookies.js

+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
import { serialize, parse } from 'cookie'
2+
3+
const TOKEN_NAME = 'token'
4+
5+
export const MAX_AGE = 60 * 60 * 8 // 8 hours
6+
7+
export function setTokenCookie(res, token) {
8+
const cookie = serialize(TOKEN_NAME, token, {
9+
maxAge: MAX_AGE,
10+
expires: new Date(Date.now() + MAX_AGE * 1000),
11+
httpOnly: true,
12+
secure: process.env.NODE_ENV === 'production',
13+
path: '/',
14+
sameSite: 'lax',
15+
})
16+
17+
res.setHeader('Set-Cookie', cookie)
18+
}
19+
20+
export function removeTokenCookie(res) {
21+
const cookie = serialize(TOKEN_NAME, '', {
22+
maxAge: -1,
23+
path: '/',
24+
})
25+
26+
res.setHeader('Set-Cookie', cookie)
27+
}
28+
29+
export function parseCookies(req) {
30+
// For API Routes we don't need to parse the cookies.
31+
if (req.cookies) return req.cookies
32+
33+
// For pages we do need to parse the cookies.
34+
const cookie = req.headers?.cookie
35+
return parse(cookie || '')
36+
}
37+
38+
export function getTokenCookie(req) {
39+
const cookies = parseCookies(req)
40+
return cookies[TOKEN_NAME]
41+
}

lib/auth.js

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import Iron from '@hapi/iron'
2+
import { MAX_AGE, setTokenCookie, getTokenCookie } from './auth-cookies'
3+
4+
const TOKEN_SECRET = process.env.TOKEN_SECRET
5+
6+
export async function setLoginSession(res, session) {
7+
const createdAt = Date.now()
8+
// Create a session object with a max age that we can validate later
9+
const obj = { ...session, createdAt, maxAge: MAX_AGE }
10+
const token = await Iron.seal(obj, TOKEN_SECRET, Iron.defaults)
11+
12+
setTokenCookie(res, token)
13+
}
14+
15+
export async function getLoginSession(req) {
16+
const token = getTokenCookie(req)
17+
18+
if (!token) return
19+
20+
const session = await Iron.unseal(token, TOKEN_SECRET, Iron.defaults)
21+
const expiresAt = session.createdAt + session.maxAge * 1000
22+
23+
// Validate the expiration date of the session
24+
if (Date.now() > expiresAt) {
25+
throw new Error('Session expired')
26+
}
27+
28+
return session
29+
}

lib/hooks.js

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import { useEffect } from 'react'
2+
import Router from 'next/router'
3+
import useSWR from 'swr'
4+
5+
const fetcher = (url) =>
6+
fetch(url)
7+
.then((r) => r.json())
8+
.then((data) => {
9+
return { user: data?.user || null }
10+
})
11+
12+
export function useUser({ redirectTo, redirectIfFound } = {}) {
13+
const { data, error } = useSWR('/api/user', fetcher)
14+
const user = data?.user
15+
const finished = Boolean(data)
16+
const hasUser = Boolean(user)
17+
18+
useEffect(() => {
19+
if (!redirectTo || !finished) return
20+
if (
21+
// If redirectTo is set, redirect if the user was not found.
22+
(redirectTo && !redirectIfFound && !hasUser) ||
23+
// If redirectIfFound is also set, redirect if the user was found
24+
(redirectIfFound && hasUser)
25+
) {
26+
Router.push(redirectTo)
27+
}
28+
}, [redirectTo, redirectIfFound, finished, hasUser])
29+
30+
return error ? null : user
31+
}

lib/magic.js

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
const { Magic } = require('@magic-sdk/admin')
2+
3+
export const magic = new Magic(process.env.MAGIC_SECRET_KEY)

0 commit comments

Comments
 (0)