Last active
January 10, 2025 00:52
-
-
Save zachshallbetter/669729a37e66f277147b2fb864d921ee to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// In this file, you can use the App component to protect routes that require authentication or authorization. | |
// Use the `useRouter` and `useEffect` hooks to check the user's status and redirect them if necessary. | |
import { useRouter } from 'next/router'; | |
import { useEffect } from 'react'; | |
function MyApp({ Component, pageProps }) { | |
const router = useRouter(); | |
useEffect(() => { | |
const handleRouteChange = (url) => { | |
// Add your own logic here to check if the user is authenticated | |
const userIsAuthenticated = checkUserAuthentication(); | |
if (!userIsAuthenticated && url === '/protected-page') { | |
router.replace('/login'); | |
} | |
}; | |
router.events.on('routeChangeStart', handleRouteChange); | |
return () => { | |
router.events.off('routeChangeStart', handleRouteChange); | |
}; | |
}, []); | |
return <Component {...pageProps} />; | |
} | |
export default MyApp; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// In this file, you can define middleware to protect pages, components, and APIs. | |
// Use the `authMiddleware(req)` function to check if the user is authenticated. | |
import { NextResponse } from 'next/server'; | |
export function authMiddleware(req) { | |
// Add your own logic here to check if the user is authenticated | |
const userIsAuthenticated = checkUserAuthentication(); | |
if (!userIsAuthenticated) { | |
return NextResponse.redirect('/login'); | |
} | |
return NextResponse.next(); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// In this file, you can define the data fetching logic for server-side rendered pages. | |
// This function is called on every request, so you can fetch data dynamically based on the request. | |
export async function getServerSideProps() { | |
const data = await unstable_cache('your-api-url'); | |
return { props: { data } }; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// In this file, you can define the paths for which you want to pre-render pages at build time. | |
// For example, if you have a dynamic route like `/products/[id]`, you can specify which `id` values | |
// you want to pre-render. | |
export async function getStaticPaths() { | |
// Your logic here to fetch the list of dynamic paths | |
// Example: Fetch a list of product IDs from your API | |
const productIds = await fetchProductIdsFromAPI(); | |
// Map the product IDs to an array of objects with the `params` key | |
const paths = productIds.map((id) => ({ | |
params: { id: id.toString() }, | |
})); | |
// Return the paths to be pre-rendered | |
return { | |
paths, | |
// If you set `fallback` to `false`, only the paths returned by `getStaticPaths` will be pre-rendered. | |
// If you set `fallback` to `true`, Next.js will also pre-render pages on-demand for paths that were not | |
// generated at build time. | |
fallback: false, // or true | |
}; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// In this file, you can define the data fetching logic for pre-rendered pages. | |
// The `context` parameter can be used to access the `params` object, which contains | |
// the dynamic route parameters (e.g., `id` in `/products/[id]`). | |
export async function getStaticProps(context) { | |
// Your logic here to fetch data based on the `productId` | |
// Example: Fetch product details from your API | |
const productDetails = await fetchProductDetailsById(productId); | |
// Return the data as props to be used in the page component | |
return { | |
props: { | |
product: productDetails, | |
}, | |
// You can also specify `revalidate` to control how often the page should be re-generated | |
// after build time. It's the number of seconds. | |
revalidate: 60, // This page will be re-generated every 60 seconds | |
}; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// In this file, you can use middleware to protect routes in Next.js. | |
// Use the `middleware(req)` function to check if the user is authenticated. | |
import { NextRequest, NextResponse } from 'next/server'; | |
export default function middleware(req) { | |
// Add your own logic here to check if the user is authenticated | |
const userIsAuthenticated = checkUserAuthentication(); | |
if (!userIsAuthenticated) { | |
return NextResponse.redirect('/login'); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Protecting Routes in Next.js with App Router | |
This Gist provides code examples and explanations for protecting routes in a Next.js application using the App Router feature in Next.js 13.4. It covers the latest features, including Middleware, exportMode, unstable_cache, and more. This guide is intended for senior developers with a good understanding of Next.js and React. | |
## Article Source | |
The code and explanations in this Gist are based on the Medium article [Protecting Routes in Next.js with App Router](https://medium.com/@zachshallbetter/protecting-routes-in-next-js-with-app-router-53c3409c0655) by Zach Shallbetter. For detailed context and explanations, please refer to the original article. | |
## Code Examples | |
### Example 1: Replacing output with exportMode | |
```javascript | |
// next.config.js | |
module.exports = { | |
exportMode: 'your-value', | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment