diff --git a/README.md b/README.md index af60f0e..9f4e770 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186). -_1358 TILs and counting..._ +_1359 TILs and counting..._ --- @@ -592,6 +592,7 @@ _1358 TILs and counting..._ - [Define URL Redirects In The Next Config](nextjs/define-url-redirects-in-the-next-config.md) - [Make Environment Variable Publicly Available](nextjs/make-environment-variable-publicly-available.md) - [Push A Route With A URL Object](nextjs/push-a-route-with-a-url-object.md) +- [Redirect An Unauthorized User](nextjs/redirect-an-unauthorized-user.md) - [Remove A Query Param From The URL](nextjs/remove-a-query-param-from-the-url.md) - [Ship Public Assets With A Next.js App](nextjs/ship-public-assets-with-a-nextjs-app.md) diff --git a/nextjs/redirect-an-unauthorized-user.md b/nextjs/redirect-an-unauthorized-user.md new file mode 100644 index 0000000..891d70b --- /dev/null +++ b/nextjs/redirect-an-unauthorized-user.md @@ -0,0 +1,50 @@ +# Redirect An Unauthorized User + +With the Page Router in earlier next version, we could do a server-side +authorization check in `getServerSideProps` and then return a +[`redirect`](https://nextjs.org/docs/pages/api-reference/functions/get-server-side-props#redirect) +response in order to redirect the user to a page they are authorized for. + +That might look something like this: + +```javascript +export async function getServerSideProps(context) { + const session = await getServerAuthSession() + const ability = getAbility({user: session?.user}) + + if (!ability.can('create', 'Post')) { + return { + redirect: { + destination: '/posts', + permanent: false, + }, + } + } + + return { + props: {}, + } +} +``` + +We can achieve the same thing with the App Router, but with a bit less code. +The `next/navigation` package has a [`redirect` +function](https://nextjs.org/docs/app/api-reference/functions/redirect) that we +can invoke directly in a component. This will redirect the user instead of +rendering the component to HTML. + +```javascript +import { redirect } from 'next/navigation' + +export default async function CreatePost() { + const session = await getServerAuthSession() + const ability = getAbility({user: session?.user}) + + if (!ability.can('create', 'Post')) { + redirect('/posts') + } + + // JSX follows + return (...) +} +```