Unverified Commit 9e978cf6 authored by Dev Agrawal's avatar Dev Agrawal Committed by GitHub

with-clerk example updated to app router (#49717)

<!-- Thanks for opening a PR! Your contribution is much appreciated.
To make sure your PR is handled as smoothly as possible we request that
you follow the checklist sections below.
Choose the right checklist for the change(s) that you're making:

## For Contributors

### Improving Documentation or adding/fixing Examples

- The "examples guidelines" are followed from our contributing doc
https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md
- Make sure the linting passes by running `pnpm build && pnpm lint`. See
https://github.com/vercel/next.js/blob/canary/contributing/repository/linting.md

### Fixing a bug

- Related issues linked using `fixes #number`
- Tests added. See:
https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md

### Adding a feature

- Implements an existing feature request or RFC. Make sure the feature
request has been accepted for implementation before opening a PR. (A
discussion must be opened, see
https://github.com/vercel/next.js/discussions/new?category=ideas)
- Related issues/discussions are linked using `fixes #number`
- e2e tests added
(https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs
- Documentation added
- Telemetry added. In case of a feature if it's used or not.
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md



## For Maintainers

- Minimal description (aim for explaining to someone not on the team to
understand the PR)
- When linking to a Slack thread, you might want to share details of the
conclusion
- Link both the Linear (Fixes NEXT-xxx) and the GitHub issues
- Add review comments if necessary to explain to the reviewer the logic
behind a change

### What?
Updates the `with-clerk` example to use the app router and latest
version of `@clerk/nextjs`
### Why?

### How?

Closes NEXT-
Fixes #

-->

Updates the `with-clerk` example to use the app router and latest
version of `@clerk/nextjs`
parent af338079
NEXT_PUBLIC_CLERK_FRONTEND_API=your_clerk_frontend_api NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=your_clerk_pub_key
CLERK_API_KEY=your_clerk_api_key CLERK_SECRET_KEY=your_clerk_secret_key
CLERK_JWT_KEY=your_clerk_jwt_key
\ No newline at end of file NEXT_PUBLIC_CLERK_SIGN_IN_URL=/sign-in
NEXT_PUBLIC_CLERK_SIGN_UP_URL=/sign-up
NEXT_PUBLIC_CLERK_AFTER_SIGN_IN_URL=/
NEXT_PUBLIC_CLERK_AFTER_SIGN_UP_URL=/
\ No newline at end of file
'use client'
import { SignedIn, SignedOut } from '@clerk/nextjs'
import { useEffect, useState } from 'react'
import styles from '../styles/Home.module.css'
import '../styles/prism.css'
declare global {
interface Window {
Prism: any
}
}
const apiSample = `import { auth } from "@clerk/nextjs";
import { NextResponse } from "next/server";
export async function GET(request: Request) {
const { userId, sessionId } = auth()
if(!sessionId) {
return NextResponse.json({ id: null }, { status: 401 })
}
return NextResponse.json({ id: userId }, { status: 200 })
}`
export const APIRequest = () => {
useEffect(() => {
if (window.Prism) {
window.Prism.highlightAll()
}
})
const [response, setResponse] = 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
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>app/api/getAuthenticatedUserId/route.ts</h4>
<pre>
<code className="language-js">{apiSample}</code>
</pre>
</div>
)
}
import { auth } from '@clerk/nextjs'
import { NextResponse } from 'next/server'
export async function GET(request: Request) {
const { userId, sessionId } = auth()
if (!sessionId) {
return NextResponse.json({ id: null }, { status: 401 })
}
return NextResponse.json({ id: userId }, { status: 200 })
}
import styles from '../styles/Header.module.css' import '../styles/globals.css'
import { ClerkProvider, SignedIn, SignedOut, UserButton } from '@clerk/nextjs'
import { Inter } from 'next/font/google'
import Image from 'next/image' import Image from 'next/image'
import Script from 'next/script'
import styles from '../styles/Header.module.css'
import Link from 'next/link' import Link from 'next/link'
import { SignedIn, SignedOut, UserButton } from '@clerk/nextjs'
// Header component using <SignedIn> & <SignedOut>. const inter = Inter({ subsets: ['latin'] })
//
// The SignedIn and SignedOut components are used to control rendering depending export const metadata = {
// on whether or not a visitor is signed in. title: 'Create Next App',
// description: 'Generated by create next app',
// https://docs.clerk.dev/frontend/react/signedin-and-signedout }
const Header = () => ( const Header = () => (
<header className={styles.header}> <header className={styles.header}>
<div className={styles.left}> <div className={styles.left}>
...@@ -22,10 +26,28 @@ const Header = () => ( ...@@ -22,10 +26,28 @@ const Header = () => (
<Link href="/sign-in">Sign in</Link> <Link href="/sign-in">Sign in</Link>
</SignedOut> </SignedOut>
<SignedIn> <SignedIn>
<UserButton userProfileURL="/user" afterSignOutAll="/" /> <UserButton />
</SignedIn> </SignedIn>
</div> </div>
</header> </header>
) )
export default Header export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en">
<head></head>
<ClerkProvider>
<body className={inter.className}>
<Header />
<main>{children}</main>
</body>
</ClerkProvider>
<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" />
</html>
)
}
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/nextjs' import { SignedIn, SignedOut } from '@clerk/nextjs'
import styles from '../styles/Home.module.css'
import Link from 'next/link'
import Head from 'next/head'
import { APIRequest } from './api-request'
const ClerkFeatures = () => ( const ClerkFeatures = () => (
<Link href="/user" className={styles.cardContent}> <Link href="/user" className={styles.cardContent}>
...@@ -36,16 +36,6 @@ const SignupLink = () => ( ...@@ -36,16 +36,6 @@ const SignupLink = () => (
</Link> </Link>
) )
const apiSample = `import { getAuth } from '@clerk/nextjs/server'
export default function handler(req, res) {
const { sessionId, userId } = getAuth(req);
if (!sessionId) {
return res.status(401).json({ id: null });
}
return res.status(200).json({ id: userId });
}`
// Main component using <SignedIn> & <SignedOut>. // Main component using <SignedIn> & <SignedOut>.
// //
// The SignedIn and SignedOut components are used to control rendering depending // The SignedIn and SignedOut components are used to control rendering depending
...@@ -112,73 +102,6 @@ const Main = () => ( ...@@ -112,73 +102,6 @@ const Main = () => (
</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 // Footer component
const Footer = () => ( const Footer = () => (
<footer className={styles.footer}> <footer className={styles.footer}>
...@@ -193,7 +116,8 @@ const Footer = () => ( ...@@ -193,7 +116,8 @@ const Footer = () => (
</footer> </footer>
) )
const Home = () => ( export default function Home() {
return (
<div className={styles.container}> <div className={styles.container}>
<Head> <Head>
<title>Create Next App</title> <title>Create Next App</title>
...@@ -206,6 +130,5 @@ const Home = () => ( ...@@ -206,6 +130,5 @@ const Home = () => (
<Main /> <Main />
<Footer /> <Footer />
</div> </div>
) )
}
export default Home
import { SignIn } from '@clerk/nextjs'
export default function Page() {
return <SignIn />
}
import { SignUp } from '@clerk/nextjs'
export default function Page() {
return <SignUp />
}
import { UserProfile } from '@clerk/nextjs' import { UserProfile } from '@clerk/nextjs'
const UserProfilePage = () => <UserProfile path="/user" routing="path" /> const UserProfilePage = () => <UserProfile />
export default UserProfilePage export default UserProfilePage
import Header from './Header'
const Layout = ({ children }) => (
<>
<Header />
<main>{children}</main>
</>
)
export default Layout
import { withClerkMiddleware } from '@clerk/nextjs/server'
import { NextResponse } from 'next/server'
export default withClerkMiddleware((_req) => {
return NextResponse.next()
})
export const config = {
matcher: ['/api/getAuthenticatedUserId'],
}
import { authMiddleware } from '@clerk/nextjs'
export default authMiddleware({
publicRoutes: ['/', '/api/getAuthenticatedUserId'],
})
export const config = {
matcher: ['/((?!.*\\..*|_next).*)', '/'],
}
/** @type {import('next').NextConfig} */
const nextConfig = {}
module.exports = nextConfig
...@@ -6,9 +6,13 @@ ...@@ -6,9 +6,13 @@
"start": "next start" "start": "next start"
}, },
"dependencies": { "dependencies": {
"@clerk/nextjs": "4.5.1", "@clerk/nextjs": "^4.17.3",
"next": "latest", "@types/node": "20.1.3",
"@types/react": "18.2.6",
"@types/react-dom": "18.2.4",
"next": "13.4.2",
"react": "18.2.0", "react": "18.2.0",
"react-dom": "18.2.0" "react-dom": "18.2.0",
"typescript": "5.0.4"
} }
} }
import '../styles/globals.css'
import { ClerkProvider, SignedIn, SignedOut } from '@clerk/nextjs'
import { useRouter } from 'next/router'
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
* every page requires authentication. Use this naming strategy:
* "/" for pages/index.js
* "/foo" for pages/foo/index.js
* "/foo/bar" for pages/foo/bar.js
* "/foo/[...bar]" for pages/foo/[...bar].js
*/
const publicPages = ['/', '/sign-in/[[...index]]', '/sign-up/[[...index]]']
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>
<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} />
) : (
<>
<SignedIn>
<Component {...pageProps} />
</SignedIn>
<SignedOut>
<main>
<p>
Please <Link href="/sign-in">sign in</Link> to access this
page.
</p>
</main>
</SignedOut>
</>
)}
</Layout>
</ClerkProvider>
)
}
export default MyApp
import { Html, Head, Main, NextScript } from 'next/document'
export default function Document() {
return (
<Html>
<Head>
<link
href="https://fonts.googleapis.com/css2?family=Source+Sans+Pro:wght@400;600&display=swap"
rel="stylesheet"
/>
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
)
}
import { getAuth } from '@clerk/nextjs/server'
export default function handler(req, res) {
const { sessionId, userId } = getAuth(req)
if (!sessionId) {
return res.status(401).json({ id: null })
}
return res.status(200).json({ id: userId })
}
import { SignIn } from '@clerk/nextjs'
const SignInPage = () => (
<SignIn path="/sign-in" routing="path" signUpUrl="/sign-up" />
)
export default SignInPage
import { SignUp } from '@clerk/nextjs'
const SignUpPage = () => (
<SignUp path="/sign-up" routing="path" signInUrl="/sign-in" />
)
export default SignUpPage
<svg width="283" height="64" viewBox="0 0 283 64" fill="none"
xmlns="http://www.w3.org/2000/svg">
<path d="M141.04 16c-11.04 0-19 7.2-19 18s8.96 18 20 18c6.67 0 12.55-2.64 16.19-7.09l-7.65-4.42c-2.02 2.21-5.09 3.5-8.54 3.5-4.79 0-8.86-2.5-10.37-6.5h28.02c.22-1.12.35-2.28.35-3.5 0-10.79-7.96-17.99-19-17.99zm-9.46 14.5c1.25-3.99 4.67-6.5 9.45-6.5 4.79 0 8.21 2.51 9.45 6.5h-18.9zM248.72 16c-11.04 0-19 7.2-19 18s8.96 18 20 18c6.67 0 12.55-2.64 16.19-7.09l-7.65-4.42c-2.02 2.21-5.09 3.5-8.54 3.5-4.79 0-8.86-2.5-10.37-6.5h28.02c.22-1.12.35-2.28.35-3.5 0-10.79-7.96-17.99-19-17.99zm-9.45 14.5c1.25-3.99 4.67-6.5 9.45-6.5 4.79 0 8.21 2.51 9.45 6.5h-18.9zM200.24 34c0 6 3.92 10 10 10 4.12 0 7.21-1.87 8.8-4.92l7.68 4.43c-3.18 5.3-9.14 8.49-16.48 8.49-11.05 0-19-7.2-19-18s7.96-18 19-18c7.34 0 13.29 3.19 16.48 8.49l-7.68 4.43c-1.59-3.05-4.68-4.92-8.8-4.92-6.07 0-10 4-10 10zm82.48-29v46h-9V5h9zM36.95 0L73.9 64H0L36.95 0zm92.38 5l-27.71 48L73.91 5H84.3l17.32 30 17.32-30h10.39zm58.91 12v9.69c-1-.29-2.06-.49-3.2-.49-5.81 0-10 4-10 10V51h-9V17h9v9.2c0-5.08 5.91-9.2 13.2-9.2z" fill="#000"/>
</svg>
/**
* prism.js default theme for JavaScript, CSS and HTML
* Based on dabblet (http://dabblet.com)
* @author Lea Verou
*/
code[class*='language-'],
pre[class*='language-'] {
color: black;
background: none;
text-shadow: 0 1px white;
font-family: Consolas, Monaco, 'Andale Mono', 'Ubuntu Mono', monospace;
font-size: 1em;
text-align: left;
white-space: pre;
word-spacing: normal;
word-break: normal;
word-wrap: normal;
line-height: 1.5;
-moz-tab-size: 4;
-o-tab-size: 4;
tab-size: 4;
-webkit-hyphens: none;
-moz-hyphens: none;
-ms-hyphens: none;
hyphens: none;
}
pre[class*='language-']::-moz-selection,
pre[class*='language-'] ::-moz-selection,
code[class*='language-']::-moz-selection,
code[class*='language-'] ::-moz-selection {
text-shadow: none;
background: #b3d4fc;
}
pre[class*='language-']::selection,
pre[class*='language-'] ::selection,
code[class*='language-']::selection,
code[class*='language-'] ::selection {
text-shadow: none;
background: #b3d4fc;
}
@media print {
code[class*='language-'],
pre[class*='language-'] {
text-shadow: none;
}
}
/* Code blocks */
pre[class*='language-'] {
padding: 1em;
margin: 0.5em 0;
overflow: auto;
}
:not(pre) > code[class*='language-'],
pre[class*='language-'] {
background: #f5f2f0;
}
/* Inline code */
:not(pre) > code[class*='language-'] {
padding: 0.1em;
border-radius: 0.3em;
white-space: normal;
}
.token.comment,
.token.prolog,
.token.doctype,
.token.cdata {
color: slategray;
}
.token.punctuation {
color: #999;
}
.token.namespace {
opacity: 0.7;
}
.token.property,
.token.tag,
.token.boolean,
.token.number,
.token.constant,
.token.symbol,
.token.deleted {
color: #905;
}
.token.selector,
.token.attr-name,
.token.string,
.token.char,
.token.builtin,
.token.inserted {
color: #690;
}
.token.operator,
.token.entity,
.token.url,
.language-css .token.string,
.style .token.string {
color: #9a6e3a;
/* This background color was intended by the author of this theme. */
background: hsla(0, 0%, 100%, 0.5);
}
.token.atrule,
.token.attr-value,
.token.keyword {
color: #07a;
}
.token.function,
.token.class-name {
color: #dd4a68;
}
.token.regex,
.token.important,
.token.variable {
color: #e90;
}
.token.important,
.token.bold {
font-weight: bold;
}
.token.italic {
font-style: italic;
}
.token.entity {
cursor: help;
}
{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": ["./*"]
}
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"exclude": ["node_modules"]
}
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