Unverified Commit 713a5aa7 authored by Colin Sidoti's avatar Colin Sidoti Committed by GitHub

Use new @clerk/nextjs package in with-clerk example, update Next.js authentication docs (#28906)

* Update headings to clarify that we're describing. Add heading for Authentication API Routes

* Start adding API route examples

* Start adding API route examples

* Start adding API route examples

* Start adding API route examples

* auth: Replace clerk packages with @clerk/nextjs

* Add API authentication example to with-clerk

* Fix footer links

* Proofread, ensure consistency

* Update example's props to use new version

* Update example links

* Add rel tag to _blank link

* Obscure the authentication provider in the example

* Replace example

* Reset authentication docs, list Clerk as vendor

* Re-fix typo

* Change sample to example

* Add the example

* Update examples/with-clerk/package.json
Co-authored-by: 's avatarLee Robinson <me@leerob.io>
Co-authored-by: 's avatarPeter Perlepes <p.perlepes@gmail.com>
Co-authored-by: 's avatarLee Robinson <me@leerob.io>
parent e9cafaa3
......@@ -141,6 +141,7 @@ To see examples with other authentication providers, check out the [examples fol
<li><a href="https://github.com/vercel/next.js/tree/canary/examples/with-userbase">with-userbase</a></li>
<li><a href="https://github.com/vercel/next.js/tree/canary/examples/with-supertokens">with-supertokens</a></li>
<li><a href="https://github.com/vercel/next.js/tree/canary/examples/with-nhost-auth-realtime-graphql">with-nhost-auth-realtime-graphql</a></li>
<li><a href="https://github.com/vercel/next.js/tree/canary/examples/with-clerk">with-clerk</a></li>
</ul>
</details>
......
NEXT_PUBLIC_CLERK_FRONTEND_API=your-frontend-api
CLERK_API_KEY=your-api-key
\ No newline at end of file
# Clerk.dev Example
# Clerk and Next.js Example
This example shows how to use [Clerk.dev](https://www.clerk.dev/?utm_source=github&utm_medium=nextjs-examples&utm_campaign=nextjs) with Next.js. The example features adding sign up, sign in, and profile management to your Next.js application in minutes.
This example shows how to use [Clerk](https://www.clerk.dev/?utm_source=github&utm_medium=nextjs-examples&utm_campaign=nextjs) with Next.js. The example features adding sign up, sign in, profile management, and an authenticated API route to your Next.js application.
## Demo
A hosted demo of this example is available at [clerk-nextjs-example.vercel.app](https://clerk-nextjs-example.vercel.app)
## Deploy your own
......@@ -18,10 +22,18 @@ npx create-next-app --example with-clerk with-clerk-app
yarn create next-app --example with-clerk with-clerk-app
```
To run the example locally you need to:
1. Sign up at [Clerk.dev](https://www.clerk.dev/?utm_source=github&utm_medium=starter_repos&utm_campaign=nextjs_starter).
2. Go to [Clerk's dashboard](https://dashboard.clerk.dev/?utm_source=github&utm_medium=starter_repos&utm_campaign=nextjs_starter) and create an application.
3. Set the required Clerk environment variables from your Clerk project as shown at [the example env file](./.env.local.example).
4. `yarn` to install the required dependencies.
5. `yarn dev` to launch the development server.
## Learn More
To learn more about Clerk.dev and Next.js, take a look at the following resources:
- [Quick start](https://docs.clerk.dev/frontend/quick-starts/next.js)
- [Quick start](https://docs.clerk.dev/get-started/nextjs)
- [Clerk.dev Documentation](https://docs.clerk.dev/) - learn about Clerk.dev features and API.
- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
import styles from '../styles/Header.module.css'
import Image from 'next/image'
import Link from 'next/link'
import { SignedIn, SignedOut, UserButton } from '@clerk/clerk-react'
import { SignedIn, SignedOut, UserButton } from '@clerk/nextjs'
// Header component using <SignedIn> & <SignedOut>.
//
......
......@@ -6,10 +6,9 @@
"start": "next start"
},
"dependencies": {
"@clerk/clerk-react": "1.7.0",
"@clerk/clerk-sdk-node": "0.3.0",
"next": "10.0.9",
"react": "^17.0.2",
"react-dom": "^17.0.2"
"@clerk/nextjs": "1.0.1",
"next": "latest",
"react": "17.0.2",
"react-dom": "17.0.2"
}
}
import '../styles/globals.css'
import { ClerkProvider, SignedIn, SignedOut } from '@clerk/clerk-react'
import { ClerkProvider, SignedIn, SignedOut } from '@clerk/nextjs'
import { useRouter } from 'next/router'
import { useEffect } from 'react'
import Layout from '../components/Layout'
import Head from 'next/head'
import Script from 'next/script'
import Link from 'next/link'
/**
* List pages you want to be publicly accessible, or leave empty if
......@@ -14,26 +16,23 @@ import Layout from '../components/Layout'
*/
const publicPages = ['/', '/sign-in/[[...index]]', '/sign-up/[[...index]]']
const RedirectToSignIn = () => {
const router = useRouter()
useEffect(() => {
router.push('/sign-in')
})
return null
}
const MyApp = ({ Component, pageProps }) => {
const router = useRouter()
/**
* If the current route is listed as public, render it directly.
* Otherwise, use Clerk to require authentication.
*/
return (
<ClerkProvider
frontendApi={process.env.NEXT_PUBLIC_CLERK_FRONTEND_API}
scriptUrl={process.env.NEXT_PUBLIC_CLERK_JS}
navigate={(to) => router.push(to)}
>
<ClerkProvider>
<Head>
<link
href="https://cdn.jsdelivr.net/npm/prismjs@1/themes/prism.css"
rel="stylesheet"
/>
</Head>
<Script src="https://cdn.jsdelivr.net/npm/prismjs@1/components/prism-core.min.js" />
<Script src="https://cdn.jsdelivr.net/npm/prismjs@1/plugins/autoloader/prism-autoloader.min.js" />
<Layout>
{publicPages.includes(router.pathname) ? (
<Component {...pageProps} />
......@@ -43,7 +42,15 @@ const MyApp = ({ Component, pageProps }) => {
<Component {...pageProps} />
</SignedIn>
<SignedOut>
<RedirectToSignIn />
<main>
<p>
Please{' '}
<Link href="/sign-in">
<a>sign in</a>
</Link>{' '}
to access this page.
</p>
</main>
</SignedOut>
</>
)}
......
import { withSession } from '@clerk/nextjs/api'
export default withSession((req, res) => {
res.statusCode = 200
if (req.session) {
res.json({ id: req.session.userId })
} else {
res.json({ id: null })
}
})
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
const hello = (req, res) => {
res.statusCode = 200
res.json({ name: 'John Doe' })
}
export default hello
import React from 'react'
import Head from 'next/head'
import Link from 'next/link'
import styles from '../styles/Home.module.css'
import { SignedIn, SignedOut } from '@clerk/clerk-react'
import { SignedIn, SignedOut } from '@clerk/nextjs'
const ClerkFeatures = () => (
<Link href="/user">
......@@ -39,6 +40,17 @@ const SignupLink = () => (
</Link>
)
const apiSample = `import { withSession } from '@clerk/nextjs/api'
export default withSession((req, res) => {
res.statusCode = 200
if (req.session) {
res.json({ id: req.session.userId })
} else {
res.json({ id: null })
}
})`
// Main component using <SignedIn> & <SignedOut>.
//
// The SignedIn and SignedOut components are used to control rendering depending
......@@ -79,6 +91,8 @@ const Main = () => (
</div>
</div>
<APIRequest />
<div className={styles.links}>
<Link href="https://docs.clerk.dev">
<a target="_blank" rel="noreferrer" className={styles.link}>
......@@ -94,17 +108,82 @@ const Main = () => (
</main>
)
const APIRequest = () => {
React.useEffect(() => {
if (window.Prism) {
window.Prism.highlightAll()
}
})
const [response, setResponse] = React.useState(
'// Click above to run the request'
)
const makeRequest = async () => {
setResponse('// Loading...')
try {
const res = await fetch('/api/getAuthenticatedUserId')
const body = await res.json()
setResponse(JSON.stringify(body, null, ' '))
} catch (e) {
setResponse(
'// There was an error with the request. Please contact support@clerk.dev'
)
}
}
return (
<div className={styles.backend}>
<h2>API request example</h2>
<div className={styles.card}>
<button
target="_blank"
rel="noreferrer"
className={styles.cardContent}
onClick={() => makeRequest()}
>
<img src="/icons/server.svg" />
<div>
<h3>fetch('/api/getAuthenticatedUserId')</h3>
<p>
Retrieve the user ID of the signed in user, or null if there is no
user
</p>
</div>
<div className={styles.arrow}>
<img src="/icons/download.svg" />
</div>
</button>
</div>
<h4>
Response
<em>
<SignedIn>
You are signed in, so the request will return your user ID
</SignedIn>
<SignedOut>
You are signed out, so the request will return null
</SignedOut>
</em>
</h4>
<pre>
<code className="language-js">{response}</code>
</pre>
<h4>pages/api/getAuthenticatedUserId.js</h4>
<pre>
<code className="language-js">{apiSample}</code>
</pre>
</div>
)
}
// Footer component
const Footer = () => (
<footer className={styles.footer}>
<a
href="https://vercel.com?utm_source=create-next-app&utm_medium=default-template&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
Powered by{' '}
Powered by{' '}
<a href="https://clerk.dev" target="_blank" rel="noopener noreferrer">
<img src="/clerk.svg" alt="Clerk.dev" className={styles.logo} />
+
</a>
+
<a href="https://nextjs.org/" target="_blank" rel="noopener noreferrer">
<img src="/nextjs.svg" alt="Next.js" className={styles.logo} />
</a>
</footer>
......
import { SignIn } from '@clerk/clerk-react'
import { SignIn } from '@clerk/nextjs'
const SignInPage = () => (
<SignIn path="/sign-in" routing="path" signUpURL="/sign-up" />
<SignIn path="/sign-in" routing="path" signUpUrl="/sign-up" />
)
export default SignInPage
import { SignUp } from '@clerk/clerk-react'
import { SignUp } from '@clerk/nextjs'
const SignUpPage = () => (
<SignUp path="/sign-up" routing="path" signInURL="/sign-in" />
<SignUp path="/sign-up" routing="path" signInUrl="/sign-in" />
)
export default SignUpPage
import { UserProfile } from '@clerk/clerk-react'
import { UserProfile } from '@clerk/nextjs'
const UserProfilePage = () => <UserProfile path="/user" routing="path" />
......
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M3 17V20C3 21.1046 3.89543 22 5 22H19C20.1046 22 21 21.1046 21 20V17" stroke="#335BF1" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M8 12L12 16L16 12" stroke="#335BF1" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M12 2V16" stroke="#335BF1" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
</svg>
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" clip-rule="evenodd" d="M2 4C2 2.89543 2.89543 2 4 2H20C21.1046 2 22 2.89543 22 4V8C22 9.10457 21.1046 10 20 10H4C2.89543 10 2 9.10457 2 8V4Z" stroke="#335BF1" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M2 16C2 14.8954 2.89543 14 4 14H20C21.1046 14 22 14.8954 22 16V20C22 21.1046 21.1046 22 20 22H4C2.89543 22 2 21.1046 2 20V16Z" stroke="#335BF1" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
<circle cx="6" cy="6" r="1" fill="#335BF1"/>
<circle cx="6" cy="18" r="1" fill="#335BF1"/>
</svg>
......@@ -59,7 +59,7 @@
}
.cards {
margin: 2rem 0;
margin: 2rem;
}
.card {
......@@ -118,6 +118,8 @@
}
.cardContent {
background: transparent;
border: none;
display: grid;
grid-template-columns: 24px 1fr;
gap: 1em;
......@@ -186,11 +188,14 @@
display: flex;
align-items: center;
justify-content: center;
height: 100%;
}
.cardContent {
grid-template-columns: 24px 1fr 42px;
padding: 2em;
cursor: pointer;
font: inherit;
}
.links {
......@@ -212,3 +217,21 @@
border-bottom: 2px solid #335bf1;
}
}
.backend {
margin-bottom: 4rem;
}
.backend h2 {
text-align: center;
}
.backend h4 {
margin-bottom: 0;
}
.backend h4 em {
font-weight: normal;
margin-left: 0.5rem;
}
.backend pre {
font-size: 80%;
border-radius: 0.5rem;
}
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