Compare commits

...

7 Commits

Author SHA1 Message Date
Balázs Orbán
52a2bf3e28 chore(release): bump package version(s) [skip ci] 2022-11-06 06:24:30 +01:00
Balázs Orbán
180c6252d9 fix(next): build RSC+unstable_getServerSession 2022-11-06 06:09:27 +01:00
Balázs Orbán
362e981e6d chore(release): bump package version(s) [skip ci] 2022-11-06 06:07:47 +01:00
Balázs Orbán
5198eb19f7 fix(next): build RSC+unstable_getServerSession 2022-11-06 05:53:38 +01:00
Balázs Orbán
0210cfccf3 chore(release): bump package version(s) [skip ci] 2022-11-06 05:12:31 +01:00
Balázs Orbán
e90925bea0 feat(next): allow unstable_getServerSession in Server Components (#5741)
* feat(next): support Server Components with `unstable_getServerSession`

* chore: remove `.entries`

* docs(next): add documentation for RSC

* update beta docs

* chore(dev): add app dir

* fix text

* only show second warning if using with RSC

* only delete expires for RSC case
2022-11-06 04:03:26 +00:00
Leif Arriens
27a0b70d87 docs: fix import path at providers/oauth (#5725) (#5736) 2022-11-06 00:54:01 +01:00
13 changed files with 128 additions and 23 deletions

12
apps/dev/app/layout.tsx Normal file
View File

@@ -0,0 +1,12 @@
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html>
<head></head>
<body>{children}</body>
</html>
)
}

View File

@@ -0,0 +1,7 @@
import { unstable_getServerSession } from "next-auth/next"
import { authOptions } from "pages/api/auth/[...nextauth]"
export default async function Page() {
const session = await unstable_getServerSession(authOptions)
return <pre>{JSON.stringify(session, null, 2)}</pre>
}

View File

@@ -4,5 +4,6 @@ module.exports = {
config.experiments = { ...config.experiments, topLevelAwait: true }
return config
},
experimental: { appDir: true },
typescript: { ignoreBuildErrors: true },
}

View File

@@ -1,8 +1,8 @@
// This is an example of how to access a session from an API route
import { unstable_getServerSession } from "next-auth/next"
import { authOptions } from '../auth/[...nextauth]';
import { authOptions } from "../auth/[...nextauth]"
export default async (req, res) => {
const session = await unstable_getServerSession(req, res, authOptions)
res.send(JSON.stringify(session, null, 2))
const session = await unstable_getServerSession(authOptions)
res.json(session)
}

View File

@@ -1,7 +1,11 @@
{
"compilerOptions": {
"target": "esnext",
"lib": ["dom", "dom.iterable", "esnext"],
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"strict": false,
@@ -15,7 +19,20 @@
"incremental": true,
"jsx": "preserve",
"baseUrl": ".",
"plugins": [
{
"name": "next"
}
]
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
"exclude": ["node_modules", "jest.config.js"]
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts"
],
"exclude": [
"node_modules",
"jest.config.js"
]
}

View File

@@ -13,13 +13,12 @@ export default function ServerSidePage({ session }: { session: Session }) {
<h1>Server Side Rendering</h1>
<p>
This page uses the <strong>unstable_getServerSession()</strong> method
in <strong>unstable_getServerSideProps()</strong>.
in <strong>getServerSideProps()</strong>.
</p>
<p>
Using <strong>unstable_getServerSession()</strong> in{" "}
<strong>unstable_getServerSideProps()</strong> is the recommended
approach if you need to support Server Side Rendering with
authentication.
<strong>getServerSideProps()</strong> is the recommended approach if you
need to support Server Side Rendering with authentication.
</p>
<p>
The advantage of Server Side Rendering is this page does not require

View File

@@ -24,7 +24,7 @@ export const authOptions: NextAuthOptions = {
export default NextAuth(authOptions);
```
In `getServerSideProps`:
### In `getServerSideProps`:
```js
import { authOptions } from 'pages/api/auth/[...nextauth]'
import { unstable_getServerSession } from "next-auth/next"
@@ -48,7 +48,8 @@ export async function getServerSideProps(context) {
}
}
```
In API routes:
### In API Routes:
```js
import { authOptions } from 'pages/api/auth/[...nextauth]'
import { unstable_getServerSession } from "next-auth/next"
@@ -68,6 +69,24 @@ export async function handler(req, res) {
}
```
### In `app/` directory:
You can also use `unstable_getServerSession` in Next.js' server components:
```tsx
import { unstable_getServerSession } from "next-auth/next"
import { authOptions } from "pages/api/auth/[...nextauth]"
export default async function Page() {
const session = await unstable_getServerSession(authOptions)
return <pre>{JSON.stringify(session, null, 2)}</pre>
}
```
:::warning
Currently, the underlying Next.js `cookies()` method does [only provides read access](https://beta.nextjs.org/docs/api-reference/cookies) to the request cookies. This means that the `expires` value is stripped away from `session` in Server Components. Furthermore, there is a hard expiry on sessions, after which the user will be required to sign in again. (The default expiry is 30 days).
:::
## Middleware
You can use a Next.js Middleware with NextAuth.js to protect your site.

View File

@@ -83,7 +83,7 @@ TWITTER_SECRET=YOUR_TWITTER_CLIENT_SECRET
4. Now you can add the provider settings to the NextAuth.js options object. You can add as many OAuth providers as you like, as you can see `providers` is an array.
```js title="pages/api/auth/[...nextauth].js"
import TwitterProvider from "next-auth/providers/"
import TwitterProvider from "next-auth/providers/twitter"
...
providers: [
TwitterProvider({

View File

@@ -24,7 +24,7 @@ export const authOptions: NextAuthOptions = {
export default NextAuth(authOptions);
```
In `getServerSideProps`:
### In `getServerSideProps`:
```js
import { authOptions } from 'pages/api/[...nextauth]'
import { unstable_getServerSession } from "next-auth/next"
@@ -48,7 +48,8 @@ export async function getServerSideProps(context) {
}
}
```
In API routes:
### In API routes:
```js
import { authOptions } from 'pages/api/[...nextauth]'
import { unstable_getServerSession } from "next-auth/next"
@@ -68,6 +69,24 @@ export async function handler(req, res) {
}
```
### In `app/` directory:
You can also use `unstable_getServerSession` in Next.js' server components:
```tsx
import { unstable_getServerSession } from "next-auth/next"
import { authOptions } from "pages/api/auth/[...nextauth]"
export default async function Page() {
const session = await unstable_getServerSession(authOptions)
return <pre>{JSON.stringify(session, null, 2)}</pre>
}
```
:::warning
Currently, the underlying Next.js `cookies()` method does [only provides read access](https://beta.nextjs.org/docs/api-reference/cookies) to the request cookies. This means that the `expires` value is stripped away from `session` in Server Components. Furthermore, there is a hard expiry on sessions, after which the user will be required to sign in again. (The default expiry is 30 days).
:::
## Middleware
You can use a Next.js Middleware with NextAuth.js to protect your site.

View File

@@ -1,6 +1,6 @@
{
"name": "next-auth",
"version": "4.15.2",
"version": "4.16.2",
"description": "Authentication for Next.js",
"homepage": "https://next-auth.js.org",
"repository": "https://github.com/nextauthjs/next-auth.git",

View File

@@ -58,10 +58,8 @@ async function toInternalRequest(
const url = new URL(req.url)
// TODO: handle custom paths?
const nextauth = url.pathname.split("/").slice(3)
const headers = Object.fromEntries(req.headers.entries())
const query: Record<string, any> = Object.fromEntries(
url.searchParams.entries()
)
const headers = Object.fromEntries(req.headers)
const query: Record<string, any> = Object.fromEntries(url.searchParams)
query.nextauth = nextauth
return {

View File

@@ -27,7 +27,7 @@ export default async function getAuthorizationUrl({
if (typeof provider.authorization === "string") {
const parsedUrl = new URL(provider.authorization)
const parsedParams = Object.fromEntries(parsedUrl.searchParams.entries())
const parsedParams = Object.fromEntries(parsedUrl.searchParams)
params = { ...params, ...parsedParams }
} else {
params = { ...params, ...provider.authorization?.params }

View File

@@ -1,6 +1,7 @@
import { NextAuthHandler } from "../core"
import { detectHost } from "../utils/detect-host"
import { setCookie } from "./utils"
import { cookies as nextCookies, headers } from "next/headers"
import type {
GetServerSidePropsContext,
@@ -84,6 +85,7 @@ function NextAuth(
export default NextAuth
let experimentalWarningShown = false
let experimentalRSCWarningShown = false
export async function unstable_getServerSession(
...args:
| [
@@ -92,6 +94,7 @@ export async function unstable_getServerSession(
NextAuthOptions
]
| [NextApiRequest, NextApiResponse, NextAuthOptions]
| [NextAuthOptions]
): Promise<Session | null> {
if (!experimentalWarningShown && process.env.NODE_ENV !== "production") {
console.warn(
@@ -103,7 +106,33 @@ export async function unstable_getServerSession(
experimentalWarningShown = true
}
const [req, res, options] = args
const isRSC = args.length === 1
if (
!experimentalRSCWarningShown &&
isRSC &&
process.env.NODE_ENV !== "production"
) {
console.warn(
"[next-auth][warn][EXPERIMENTAL_API]",
"\n`unstable_getServerSession` is used in a React Server Component.",
`\nhttps://next-auth.js.org/configuration/nextjs#unstable_getServerSession}`,
`\nhttps://next-auth.js.org/warnings#EXPERIMENTAL_API`
)
experimentalRSCWarningShown = true
}
const [req, res, options] = isRSC
? [
{
headers: headers(),
cookies: nextCookies()
.getAll()
.reduce((acc, c) => ({ ...acc, [c.name]: c.value }), {}),
} as any,
{ getHeader() {}, setCookie() {}, setHeader() {} } as any,
args[0],
]
: args
options.secret = options.secret ?? process.env.NEXTAUTH_SECRET
@@ -123,7 +152,11 @@ export async function unstable_getServerSession(
cookies?.forEach((cookie) => setCookie(res, cookie))
if (body && typeof body !== "string" && Object.keys(body).length) {
if (status === 200) return body as Session
if (status === 200) {
// @ts-expect-error
if (isRSC) delete body.expires
return body as Session
}
throw new Error((body as any).message)
}