Skip to content

Commit

Permalink
fix: update unstable_getServerSession to getServerSession (#1155)
Browse files Browse the repository at this point in the history
* fix: update unstable_getServerSession to getServerSession

* chore: add changeset

---------

Co-authored-by: Christopher Kapic <[email protected]>
  • Loading branch information
christopher-kapic and Christopher Kapic authored Jan 31, 2023
1 parent adc8b99 commit 90955a5
Show file tree
Hide file tree
Showing 11 changed files with 23 additions and 18 deletions.
5 changes: 5 additions & 0 deletions .changeset/nasty-points-warn.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"create-t3-app": patch
---

Change unstable_getServerSession to match the updated getServerSession from next-auth (introduced in next-auth 4.19.0)
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ const createInnerTRPCContext = (opts: CreateContextOptions) => {
export const createTRPCContext = async (opts: CreateNextContextOptions) => {
const { req, res } = opts;

// Get the session from the server using the unstable_getServerSession wrapper function
// Get the session from the server using the getServerSession wrapper function
const session = await getServerAuthSession({ req, res });

return createInnerTRPCContext({
Expand Down
2 changes: 1 addition & 1 deletion cli/template/extras/src/server/api/trpc/with-auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ const createInnerTRPCContext = (opts: CreateContextOptions) => {
export const createTRPCContext = async (opts: CreateNextContextOptions) => {
const { req, res } = opts;

// Get the session from the server using the unstable_getServerSession wrapper function
// Get the session from the server using the getServerSession wrapper function
const session = await getServerAuthSession({ req, res });

return createInnerTRPCContext({
Expand Down
6 changes: 3 additions & 3 deletions www/src/pages/ar/usage/next-auth.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,15 +70,15 @@ declare module "next-auth" {

يُمكن فَعل هذا في خطوتين:

1. للحصول علي Object الـ Session يمكنك استخدام unstable_getserversession، لا تقلق فهي امنه unstable تعني انها يمكن ان تتغير في المستقبل.
نفضل unstable_getserversession عن getSession لانها تعمل علي الخام فلا يحدث invoke غير مرغوب فيه ، قد تحملت `create-t3-app` عناء إنشاء هذه المادة عنك :
1. للحصول علي Object الـ Session يمكنك استخدام getServerSession، لا تقلق فهي امنه unstable تعني انها يمكن ان تتغير في المستقبل.
نفضل getServerSession عن getSession لانها تعمل علي الخام فلا يحدث invoke غير مرغوب فيه ، قد تحملت `create-t3-app` عناء إنشاء هذه المادة عنك :

```ts:server/common/get-server-auth-session.ts
export const getServerAuthSession = async (ctx: {
req: GetServerSidePropsContext["req"];
res: GetServerSidePropsContext["res"];
}) => {
return await unstable_getServerSession(ctx.req, ctx.res, nextAuthOptions);
return await getServerSession(ctx.req, ctx.res, nextAuthOptions);
};
```

Expand Down
2 changes: 1 addition & 1 deletion www/src/pages/en/usage/next-auth.md
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ When using NextAuth.js with tRPC, you can create reusable, protected procedures

This is done in a two step process:

1. Grab the session from the request headers using the [`getServerSession`](https://next-auth.js.org/configuration/nextjs#unstable_getserversession) function. The advantage of using `getServerSession` instead of the regular `getSession` is that it's a server-side only function and doesn't trigger unnecessary fetch calls. `create-t3-app` creates a helper function that abstracts this peculiar API away so that you don't need to import both your NextAuth.js options as well as the `getServerSession` function every time you need to access the session.
1. Grab the session from the request headers using the [`getServerSession`](https://next-auth.js.org/configuration/nextjs#getServerSession) function. The advantage of using `getServerSession` instead of the regular `getSession` is that it's a server-side only function and doesn't trigger unnecessary fetch calls. `create-t3-app` creates a helper function that abstracts this peculiar API away so that you don't need to import both your NextAuth.js options as well as the `getServerSession` function every time you need to access the session.

```ts:server/auth.ts
export const getServerAuthSession = (ctx: {
Expand Down
4 changes: 2 additions & 2 deletions www/src/pages/fr/usage/next-auth.md
Original file line number Diff line number Diff line change
Expand Up @@ -94,14 +94,14 @@ Lorsque vous utilisez NextAuth.js avec tRPC, vous pouvez créer des procédures

Cela se fait en deux étapes :

1. Récupérez la session à partir des en-têtes de requête à l'aide de la fonction [`unstable_getServerSession`](https://next-auth.js.org/configuration/nextjs#unstable_getserversession). Ne vous inquiétez pas, cette fonction est sûre à utiliser - le nom inclut "unstable" uniquement parce que l'implémentation de l'API peut changer à l'avenir. L'avantage d'utiliser `unstable_getServerSession` au lieu de `getSession` est qu'il s'agit d'une fonction côté serveur uniquement et qu'elle ne déclenche pas d'appels de récupération inutiles. `create-t3-app` crée une fonction d'assistance qui résume cette API particulière.
1. Récupérez la session à partir des en-têtes de requête à l'aide de la fonction [`getServerSession`](https://next-auth.js.org/configuration/nextjs#getServerSession). Ne vous inquiétez pas, cette fonction est sûre à utiliser - le nom inclut "unstable" uniquement parce que l'implémentation de l'API peut changer à l'avenir. L'avantage d'utiliser `getServerSession` au lieu de `getSession` est qu'il s'agit d'une fonction côté serveur uniquement et qu'elle ne déclenche pas d'appels de récupération inutiles. `create-t3-app` crée une fonction d'assistance qui résume cette API particulière.

```ts:server/auth.ts
export const getServerAuthSession = async (ctx: {
req: GetServerSidePropsContext["req"];
res: GetServerSidePropsContext["res"];
}) => {
return await unstable_getServerSession(ctx.req, ctx.res, nextAuthOptions);
return await getServerSession(ctx.req, ctx.res, nextAuthOptions);
};
```

Expand Down
4 changes: 2 additions & 2 deletions www/src/pages/no/usage/next-auth.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,14 +71,14 @@ Hvis du bruker NextAuth.js med tRPC, kan du opprette gjenbrukbare beskyttede pro

Dette skjer i to trinn:

1. Få tilgang til sesjonen fra _request-headerne_ ved å bruke funksjonen [`unstable_getServerSession`](https://next-auth.js.org/configuration/nextjs#unstable_getserversession). Ikke bekymre deg, denne funksjonen er trygg å bruke - navnet inneholder bare `unstable` fordi API-implementeringen kan endres i fremtiden. Fordelen med `unstable_getServerSession` sammenlignet med `getSession` er at det er en funksjon på serversiden og medfører ikke unødvendige kall. `create-t3-app` lager en hjelpefunksjon som abstraherer dette særegne API-et.
1. Få tilgang til sesjonen fra _request-headerne_ ved å bruke funksjonen [`getServerSession`](https://next-auth.js.org/configuration/nextjs#getServerSession). Ikke bekymre deg, denne funksjonen er trygg å bruke - navnet inneholder bare `unstable` fordi API-implementeringen kan endres i fremtiden. Fordelen med `getServerSession` sammenlignet med `getSession` er at det er en funksjon på serversiden og medfører ikke unødvendige kall. `create-t3-app` lager en hjelpefunksjon som abstraherer dette særegne API-et.

```ts:server/common/get-server-auth-session.ts
export const getServerAuthSession = async (ctx: {
req: GetServerSidePropsContext["req"];
res: GetServerSidePropsContext["res"];
}) => {
return await unstable_getServerSession(ctx.req, ctx.res, authOptions);
return await getServerSession(ctx.req, ctx.res, authOptions);
};
```

Expand Down
4 changes: 2 additions & 2 deletions www/src/pages/pl/usage/next-auth.md
Original file line number Diff line number Diff line change
Expand Up @@ -91,14 +91,14 @@ Jeżeli używasz NextAuth.js oraz tRPC, stworzyć można zabezpieczone procedury

Konfiguracja ta zachodzi w dwóch krokach:

1. Pobierz sesję z headerów zapytania korzystając z funkcji [`unstable_getServerSession`](https://next-auth.js.org/configuration/nextjs#unstable_getserversession). Nie martw się, funkcja ta jest bezpieczna do użycia - nazwa zawiera słowo `unstable` jedynie dlatego, ponieważ implementacja API w przyszłości może się zmienić. Zaletą korzystania z `unstable_getServerSession` zamiast `getSession` jest fakt, iż jest to funkcja wywoływana jedynie po stronie serwera i nie inicjuje ona żadnych niepotrzebnych zapytań. `create-t3-app` tworzy funkcję pomocniczą, która ułatwia korzystanie z `unstable_getServerSession`.
1. Pobierz sesję z headerów zapytania korzystając z funkcji [`getServerSession`](https://next-auth.js.org/configuration/nextjs#getServerSession). Nie martw się, funkcja ta jest bezpieczna do użycia - nazwa zawiera słowo `unstable` jedynie dlatego, ponieważ implementacja API w przyszłości może się zmienić. Zaletą korzystania z `getServerSession` zamiast `getSession` jest fakt, iż jest to funkcja wywoływana jedynie po stronie serwera i nie inicjuje ona żadnych niepotrzebnych zapytań. `create-t3-app` tworzy funkcję pomocniczą, która ułatwia korzystanie z `getServerSession`.

```ts:server/auth.ts
export const getServerAuthSession = async (ctx: {
req: GetServerSidePropsContext["req"];
res: GetServerSidePropsContext["res"];
}) => {
return await unstable_getServerSession(ctx.req, ctx.res, authOptions);
return await getServerSession(ctx.req, ctx.res, authOptions);
};
```

Expand Down
4 changes: 2 additions & 2 deletions www/src/pages/pt/usage/next-auth.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,14 +71,14 @@ Ao usar NextAuth.js com tRPC, você pode criar procedimentos protegidos e reutil

Isso é feito em um processo de duas etapas:

1. Pegar a sessão dos cabeçalhos de solicitação usando a função [`unstable_getServerSession`](https://next-auth.js.org/configuration/nextjs#unstable_getserversession). Não se preocupe, esta função é segura de usar - o nome inclui `unstable` apenas porque a implementação da API pode mudar no futuro. A vantagem de usar `unstable_getServerSession` em vez do `getSession` regular é que é uma função somente do lado do servidor e não aciona chamadas de busca desnecessárias. `create-t3-app` cria uma função auxiliar que abstrai essa API peculiar.
1. Pegar a sessão dos cabeçalhos de solicitação usando a função [`getServerSession`](https://next-auth.js.org/configuration/nextjs#getServerSession). Não se preocupe, esta função é segura de usar - o nome inclui `unstable` apenas porque a implementação da API pode mudar no futuro. A vantagem de usar `getServerSession` em vez do `getSession` regular é que é uma função somente do lado do servidor e não aciona chamadas de busca desnecessárias. `create-t3-app` cria uma função auxiliar que abstrai essa API peculiar.

```ts:server/common/get-server-auth-session.ts
export const getServerAuthSession = async (ctx: {
req: GetServerSidePropsContext["req"];
res: GetServerSidePropsContext["res"];
}) => {
return await unstable_getServerSession(ctx.req, ctx.res, nextAuthOptions);
return await getServerSession(ctx.req, ctx.res, nextAuthOptions);
};
```

Expand Down
4 changes: 2 additions & 2 deletions www/src/pages/ru/usage/next-auth.md
Original file line number Diff line number Diff line change
Expand Up @@ -94,14 +94,14 @@ declare module "next-auth" {

Это делается в два шага:

1. Возьмите сессию из заголовков запроса с помощью функции [`unstable_getServerSession`](https://next-auth.js.org/configuration/nextjs#unstable_getserversession). Не беспокойтесь, эта функция безопасна для использования - имя включает `unstable` только потому, что реализация API может измениться в будущем. Преимущество использования `unstable_getServerSession` вместо обычного `getSession` заключается в том, что это server-side функция и она не вызывает ненужных вызовов fetch. `create-t3-app` создает вспомогательную функцию, которая абстрагирует этот особый API.
1. Возьмите сессию из заголовков запроса с помощью функции [`getServerSession`](https://next-auth.js.org/configuration/nextjs#getServerSession). Не беспокойтесь, эта функция безопасна для использования - имя включает `unstable` только потому, что реализация API может измениться в будущем. Преимущество использования `getServerSession` вместо обычного `getSession` заключается в том, что это server-side функция и она не вызывает ненужных вызовов fetch. `create-t3-app` создает вспомогательную функцию, которая абстрагирует этот особый API.

```ts:server/auth.ts
export const getServerAuthSession = async (ctx: {
req: GetServerSidePropsContext["req"];
res: GetServerSidePropsContext["res"];
}) => {
return await unstable_getServerSession(ctx.req, ctx.res, authOptions);
return await getServerSession(ctx.req, ctx.res, authOptions);
};
```

Expand Down
4 changes: 2 additions & 2 deletions www/src/pages/zh-hans/usage/next-auth.md
Original file line number Diff line number Diff line change
Expand Up @@ -94,14 +94,14 @@ declare module "next-auth" {

这个过程可以被分为两步完成:

1. 先通过函数 [`unstable_getServerSession`](https://next-auth.js.org/configuration/nextjs#unstable_getserversession) 从请求头里获得 session。无需担心,这个函数可以被安全地使用 —— 它的名字包含 `unstable` 是因为这个 API 未来很可能会被修改而已。使用 `unstable_getServerSession` 而不是普通的 `getSession` 函数的优势是,它是一个服务端的函数,不会触发无必要的数据请求调用。 `create-t3-app` 创建了一个 `getServerAuthSession` 函数,将这个特殊的 API 抽象了出来。
1. 先通过函数 [`getServerSession`](https://next-auth.js.org/configuration/nextjs#getServerSession) 从请求头里获得 session。无需担心,这个函数可以被安全地使用 —— 它的名字包含 `unstable` 是因为这个 API 未来很可能会被修改而已。使用 `getServerSession` 而不是普通的 `getSession` 函数的优势是,它是一个服务端的函数,不会触发无必要的数据请求调用。 `create-t3-app` 创建了一个 `getServerAuthSession` 函数,将这个特殊的 API 抽象了出来。

```ts:server/auth.ts
export const getServerAuthSession = async (ctx: {
req: GetServerSidePropsContext["req"];
res: GetServerSidePropsContext["res"];
}) => {
return await unstable_getServerSession(ctx.req, ctx.res, authOptions);
return await getServerSession(ctx.req, ctx.res, authOptions);
};
```

Expand Down

1 comment on commit 90955a5

@vercel
Copy link

@vercel vercel bot commented on 90955a5 Jan 31, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.