Skip to content

docs: update nextjs quickstart #2093

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 16 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions code-examples/protect-page-login/nextjs/.env
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
NEXT_PUBLIC_ORY_SDK_URL=https://playground.projects.oryapis.com
1 change: 1 addition & 0 deletions code-examples/protect-page-login/nextjs/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
NEXT_PUBLIC_ORY_SDK_URL=https://playground.projects.oryapis.com
3 changes: 0 additions & 3 deletions code-examples/protect-page-login/nextjs/.eslintrc.json

This file was deleted.

2 changes: 1 addition & 1 deletion code-examples/protect-page-login/nextjs/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
/node_modules
/.pnp
.pnp.js
.yarn/install-state.gz

# testing
/coverage
Expand All @@ -23,7 +24,6 @@
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*

# local env files
.env*.local
Expand Down
56 changes: 3 additions & 53 deletions code-examples/protect-page-login/nextjs/README.md
Original file line number Diff line number Diff line change
@@ -1,54 +1,4 @@
This is a [Next.js](https://nextjs.org/) project bootstrapped with
[`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app).
This is a simple example application using Ory & Next.js app router.

## Getting Started

First, run the development server:

```bash
npm run dev
# or
yarn dev
# or
pnpm dev
```

Open [http://localhost:3000](http://localhost:3000) with your browser to see the
result.

You can start editing the page by modifying `pages/index.tsx`. The page
auto-updates as you edit the file.

[API routes](https://nextjs.org/docs/api-routes/introduction) can be accessed on
[http://localhost:3000/api/hello](http://localhost:3000/api/hello). This
endpoint can be edited in `pages/api/hello.ts`.

The `pages/api` directory is mapped to `/api/*`. Files in this directory are
treated as [API routes](https://nextjs.org/docs/api-routes/introduction) instead
of React pages.

This project uses
[`next/font`](https://nextjs.org/docs/basic-features/font-optimization) to
automatically optimize and load Inter, a custom Google Font.

## Learn More

To learn more about Next.js, take a look at the following resources:

- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js
features and API.
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.

You can check out
[the Next.js GitHub repository](https://github.com/vercel/next.js/) - your
feedback and contributions are welcome!

## Deploy on Vercel

The easiest way to deploy your Next.js app is to use the
[Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme)
from the creators of Next.js.

Check out our
[Next.js deployment documentation](https://nextjs.org/docs/deployment) for more
details.
To learn how to use this example, see
[Next.js integration](https://www.ory.sh/docs/getting-started/integrate-auth/nextjs)
18 changes: 18 additions & 0 deletions code-examples/protect-page-login/nextjs/app/api/hello/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { getServerSession } from "@ory/nextjs/app"
import { NextResponse } from "next/server"

export async function GET() {
// Check if the user is authenticated
const session = await getServerSession()

if (!session) {
// Return 401 if not authenticated
return NextResponse.json({ message: "Unauthorized" }, { status: 401 })
}

// Return data for authenticated users
return NextResponse.json({
message: "Hello from protected API!",
user: session?.identity?.traits,
})
}
18 changes: 18 additions & 0 deletions code-examples/protect-page-login/nextjs/app/globals.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
/* Copyright © 2024 Ory Corp */
/* SPDX-License-Identifier: Apache-2.0 */

@tailwind base;
@tailwind components;
@tailwind utilities;

body {
color: var(--foreground);
background: var(--background);
font-family: Inter, Helvetica, sans-serif;
}

@layer utilities {
.text-balance {
text-wrap: balance;
}
}
22 changes: 22 additions & 0 deletions code-examples/protect-page-login/nextjs/app/layout.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
// Copyright © 2024 Ory Corp
// SPDX-License-Identifier: Apache-2.0

import "./globals.css"
import React, { Suspense, ReactNode } from "react"
import { Inter } from "next/font/google"

const inter = Inter({ subsets: ["latin"] })

export default function RootLayout({
children,
}: Readonly<{
children: ReactNode
}>) {
return (
<html lang="en" suppressHydrationWarning className={inter.className}>
<body>
<Suspense>{children}</Suspense>
</body>
</html>
)
}
8 changes: 8 additions & 0 deletions code-examples/protect-page-login/nextjs/app/logo.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
69 changes: 69 additions & 0 deletions code-examples/protect-page-login/nextjs/app/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
"use client"

import { useEffect, useState } from "react"
import { FrontendApi, Configuration, Session } from "@ory/client-fetch"

const basePath = process.env.NEXT_PUBLIC_ORY_SDK_URL || "http://localhost:4000"
const ory = new FrontendApi(
new Configuration({
basePath,
credentials: "include",
}),
)

export default function Page() {
// highlight-start
const [session, setSession] = useState<Session | null>(null)
const [logoutUrl, setLogoutUrl] = useState<string | null>(null)

useEffect(() => {
// Check if the user is authenticated
const checkSession = async () => {
try {
const session = await ory.toSession()
setSession(session)

// Get the logout URL once we have a session
try {
const { logout_url } = await ory.createBrowserLogoutFlow()
setLogoutUrl(logout_url)
} catch (logoutError) {
console.error("Error creating logout flow:", logoutError)
}
} catch (error) {
// No valid session found, redirect to Ory login
window.location.href = `${basePath}/ui/login`
}
}

checkSession()
}, [])
// highlight-end

return (
<main className="flex min-h-screen flex-col items-center justify-between p-24">
<div className="w-full max-w-3xl">
<div className="flex justify-between items-center mb-8">
<h1 className="text-2xl font-bold">Welcome to Protected Page</h1>

{/* highlight-start */}
{/* Logout button */}
{logoutUrl && (
<a
href={logoutUrl}
className="px-4 py-2 bg-red-600 text-white rounded hover:bg-red-700 transition-colors"
>
Logout
</a>
)}
{/* highlight-end */}
</div>

<div className="p-4 rounded-lg overflow-auto">
<h2 className="text-lg font-semibold mb-2">Session Information:</h2>
<pre className="text-sm">{JSON.stringify(session, null, 2)}</pre>
</div>
</div>
</main>
)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
// Copyright © 2024 Ory Corp
// SPDX-License-Identifier: Apache-2.0

"use client"

export default function CustomCardHeader() {
return <div>My custom card header</div>
}
11 changes: 11 additions & 0 deletions code-examples/protect-page-login/nextjs/middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
// Copyright © 2024 Ory Corp
// SPDX-License-Identifier: Apache-2.0

import { createOryMiddleware } from "@ory/nextjs/middleware"
import oryConfig from "@/ory.config"

// This function can be marked `async` if using `await` inside
export const middleware = createOryMiddleware(oryConfig)

// See "Matching Paths" below to learn more
export const config = {}
2 changes: 1 addition & 1 deletion code-examples/protect-page-login/nextjs/next-env.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@
/// <reference types="next/image-types/global" />

// NOTE: This file should not be edited
// see https://nextjs.org/docs/basic-features/typescript for more information.
// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.
6 changes: 0 additions & 6 deletions code-examples/protect-page-login/nextjs/next.config.js

This file was deleted.

4 changes: 4 additions & 0 deletions code-examples/protect-page-login/nextjs/next.config.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
/** @type {import('next').NextConfig} */
const nextConfig = {}

export default nextConfig
18 changes: 18 additions & 0 deletions code-examples/protect-page-login/nextjs/ory.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
// Copyright © 2024 Ory Corp
// SPDX-License-Identifier: Apache-2.0

import type { OryConfig } from "@ory/nextjs"

const config: OryConfig = {
override: {
applicationName: "Ory Next.js App Router Example",
loginUiPath: "/auth/login",
registrationUiPath: "/auth/registration",
recoveryUiPath: "/auth/recovery",
verificationUiPath: "/auth/verification",
settingsUiPath: "/settings",
defaultRedirectUri: "/",
},
}

export default config
Loading
Loading