1. Create a New NextJS Project
npx create-next-app my-app
2. Run the Development Server
npm run dev
3. Create a New Page
// pages/index.js
import Head from 'next/head';
function HomePage() {
return (
<div>
<Head>
<title>Home Page</title>
</Head>
<h1>Welcome to my homepage!</h1>
</div>
);
}
export default HomePage;
4. Use Link Component for Client-Side Navigation
// pages/index.js
import Link from 'next/link';
function HomePage() {
return (
<div>
<Link href="/about">
<a>About</a>
</Link>
</div>
);
}
export default HomePage;
5. Use Head Component for SEO
// pages/index.js
import Head from 'next/head';
function HomePage() {
return (
<div>
<Head>
<title>Home Page</title>
<meta name="description" content="This is my homepage" />
</Head>
<h1>Welcome to my homepage!</h1>
</div>
);
}
export default HomePage;
6. Use Image Component for Image Optimization
// pages/index.js
import Image from 'next/image';
function HomePage() {
return (
<div>
<Image src="/image.jpg" width={500} height={300} />
</div>
);
}
export default HomePage;
7. Use getStaticProps for Static Site Generation
// pages/index.js
import { getStaticProps } from 'next';
function HomePage(props) {
return (
<div>
<h1>Welcome to my homepage!</h1>
</div>
);
}
export const getStaticProps = async () => {
return {
props: {},
};
};
export default HomePage;
8. Use getServerSideProps for Server-Side Rendering
// pages/index.js
import { getServerSideProps } from 'next';
function HomePage(props) {
return (
<div>
<h1>Welcome to my homepage!</h1>
</div>
);
}
export const getServerSideProps = async () => {
return {
props: {},
};
};
export default HomePage;
9. Use API Routes for Server-Side API
// pages/api/hello.js
import { NextApiRequest, NextApiResponse } from 'next';
function handler(req: NextApiRequest, res: NextApiResponse) {
res.status(200).json({ message: 'Hello World!' });
}
export default handler;
10. Use Internationalization for Multi-Language Support
// next.config.js
module.exports = {
i18n: {
locales: ['en', 'fr'],
defaultLocale: 'en',
},
};
11. Use Built-In Support for CSS Modules
// pages/index.js
import styles from '../styles/Home.module.css';
function HomePage() {
return (
<div className={styles.container}>
<h1>Welcome to my homepage!</h1>
</div>
);
}
export default HomePage;
12. Use Built-In Support for Sass
// pages/index.js
import styles from '../styles/Home.module.scss';
function HomePage() {
return (
<div className={styles.container}>
<h1>Welcome to my homepage!</h1>
</div>
);
}
export default HomePage;
13. Use Built-In Support for Less
// pages/index.js
import styles from '../styles/Home.module.less';
function HomePage() {
return (
<div className={styles.container}>
<h1>Welcome to my homepage!</h1>
</div>
);
}
export default HomePage;
14. Use Built-In Support for Stylus
// pages/index.js
import styles from '../styles/Home.module.styl';
function HomePage() {
return (
<div className={styles.container}>
<h1>Welcome to my homepage!</h1>
</div>
);
}
export default HomePage;
15. Use Custom Document for Global Styles
// pages/_document.js
import Document, { Html, Head, Main, NextScript } from 'next/document';
class MyDocument extends Document {
render() {
return (
<Html>
<Head>
<link rel="stylesheet" href="/styles/global.css" />
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
}
export default MyDocument;
16. Use Custom App for Global State
// pages/_app.js
import '../styles/global.css';
function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />;
}
export default MyApp;
17. Use Dynamic Routes
// pages/[id].js
import { useRouter } from 'next/router';
function Page() {
const router = useRouter();
const { id } = router.query;
return <h1>Post: {id}</h1>;
}
export default Page;
18. Use Static Generation with Dynamic Routes
// pages/[id].js
export async function getStaticPaths() {
return {
paths: [{ params: { id: '1' } }, { params: { id: '2' } }],
fallback: false,
};
}
export async function getStaticProps({ params }) {
return {
props: { id: params.id },
};
}
19. Use Client-Side Routing
// pages/index.js
import { useEffect } from 'react';
import { useRouter } from 'next/router';
function HomePage() {
const router = useRouter();
useEffect(() => {
router.push('/about');
}, []);
return <h1>Redirecting...</h1>;
}
export default HomePage;
20. Use Middleware for Custom Logic
// middleware.js
export function middleware(req, res, next) {
console.log('Middleware executed');
next();
}
21. Use Environment Variables
// .env.local
NEXT_PUBLIC_API_URL=https://api.example.com
22. Use Image Optimization
// pages/index.js
import Image from 'next/image';
function HomePage() {
return (
<div>
<Image src="/image.jpg" alt="My Image" width={500} height={300} />
</div>
);
}
export default HomePage;
23. Use Custom Error Pages
// pages/_error.js
function Error({ statusCode }) {
return (
<p>
{statusCode
? `An error ${statusCode} occurred on server`
: 'An error occurred on client'}
</p>
);
}
Error.getInitialProps = async ({ res, err }) => {
const statusCode = res ? res.statusCode : err ? err.statusCode : 404;
return { statusCode };
};
export default Error;
24. Use React Hooks
// pages/index.js
import { useState } from 'react';
function HomePage() {
const [count, setCount] = useState(0);
return (
<div>
<h1>Count: {count}</h1>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
export default HomePage;
25. Use Context API for State Management
// context/MyContext.js
import { createContext, useContext, useState } from 'react';
const MyContext = createContext();
export function MyProvider({ children }) {
const [value, setValue] = useState('Hello World');
return (
<MyContext.Provider value={{ value, setValue }}>
{children}
</MyContext.Provider>
);
}
export function useMyContext() {
return useContext(MyContext);
}
26. Use getInitialProps for Data Fetching
// pages/index.js
function HomePage({ data }) {
return <h1>{data}</h1>;
}
HomePage.getInitialProps = async () => {
const res = await fetch('https://api.example.com/data');
const data = await res.json();
return { data };
};
export default HomePage;
27. Use getStaticProps with Revalidation
// pages/index.js
export const getStaticProps = async () => {
const res = await fetch('https://api.example.com/data');
const data = await res.json();
return {
props: { data },
revalidate: 10, // Revalidate every 10 seconds
};
};
28. Use getServerSideProps for Dynamic Data
// pages/index.js
export const getServerSideProps = async () => {
const res = await fetch('https://api.example.com/data');
const data = await res.json();
return {
props: { data },
};
};
29. Use Custom 404 Page
// pages/404.js
function Custom404() {
return <h1>404 - Page Not Found</h1>;
}
export default Custom404;
30. Use API Routes for CRUD Operations
// pages/api/items.js
import { items } from '../../../data';
export default function handler(req, res) {
if (req.method === 'GET') {
res.status(200).json(items);
} else if (req.method === 'POST') {
const newItem = req.body;
items.push(newItem);
res.status(201).json(newItem);
}
}
31. Use SWR for Data Fetching
// pages/index.js
import useSWR from 'swr';
const fetcher = (url) => fetch(url).then((res) => res.json());
function HomePage() {
const { data, error } = useSWR('/api/data', fetcher);
if (error) return <div>Failed to load</div>;
if (!data) return <div>Loading...</div>;
return <div>{data.message}</div>;
}
export default HomePage;
32. Use TypeScript with Next.js
// pages/index.tsx
import { NextPage } from 'next';
const HomePage: NextPage = () => {
return <h1>Welcome to my homepage!</h1>;
};
export default HomePage;
33. Use Custom Server with Next.js
// server.js
const express = require('express');
const next = require('next');
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();
app.prepare().then(() => {
const server = express();
server.get('/custom', (req, res) => {
return app.render(req, res, '/custom', req.query);
});
server.all('*', (req, res) => {
return handle(req, res);
});
server.listen(3000, (err) => {
if (err) throw err;
console.log('> Ready on http://localhost:3000');
});
});
34. Use Dynamic Imports for Code Splitting
// pages/index.js
import dynamic from 'next/dynamic';
const DynamicComponent = dynamic(() => import('../components/Component'));
function HomePage() {
return <DynamicComponent />;
}
export default HomePage;
35. Use React Query for Data Fetching
// pages/index.js
import { useQuery } from 'react-query';
function HomePage() {
const { data, error, isLoading } = useQuery('data', fetchData);
if (isLoading) return <div>Loading...</div>;
if (error) return <div>Error!</div>;
return <div>{data.message}</div>;
}
async function fetchData() {
const res = await fetch('/api/data');
return res.json();
}
36. Use Next.js with Redux
// store.js
import { createStore } from 'redux';
const reducer = (state = {}, action) => {
switch (action.type) {
case 'SET_DATA':
return { ...state, data: action.payload };
default:
return state;
}
};
export const store = createStore(reducer);
37. Use Next.js with MobX
// store.js
import { makeAutoObservable } from 'mobx';
class Store {
data = '';
constructor() {
makeAutoObservable(this);
}
setData(newData) {
this.data = newData;
}
}
export const store = new Store();
38. Use Next.js with Zustand
// store.js
import create from 'zustand';
export const useStore = create((set) => ({
data: '',
setData: (newData) => set({ data: newData }),
}));
39. Use Next.js with Recoil
// store.js
import { atom } from 'recoil';
export const dataState = atom({
key: 'dataState',
default: '',
});
40. Use Next.js with Apollo Client
// pages/_app.js
import { ApolloProvider } from '@apollo/client';
import { useApollo } from '../lib/apolloClient';
function MyApp({ Component, pageProps }) {
const apolloClient = useApollo(pageProps.initialApolloProps);
return (
<ApolloProvider client={apolloClient}>
<Component {...pageProps} />
</ApolloProvider>
);
}
export default MyApp;
41. Use Next.js with GraphQL
// pages/index.js
import { gql, useQuery } from '@apollo/client';
const GET_DATA = gql`
query GetData {
data {
id
value
}
}
`;
function HomePage() {
const { loading, error, data } = useQuery(GET_DATA);
if (loading) return <p>Loading...</p>;
if (error) return <p>Error: {error.message}</p>;
return <div>{data.value}</div>;
}
export default HomePage;
42. Use Next.js with Firebase
// lib/firebase.js
import firebase from 'firebase/app';
import 'firebase/auth';
const firebaseConfig = {
apiKey: 'YOUR_API_KEY',
authDomain: 'YOUR_AUTH_DOMAIN',
projectId: 'YOUR_PROJECT_ID',
};
if (!firebase.apps.length) {
firebase.initializeApp(firebaseConfig);
}
export default firebase;
43. Use Next.js with Stripe
// pages/api/checkout.js
import Stripe from 'stripe';
const stripe = new Stripe('YOUR_SECRET_KEY');
export default async function handler(req, res) {
const session = await stripe.checkout.sessions.create({
payment_method_types: ['card'],
line_items: req.body.items,
mode: 'payment',
success_url: `${req.headers.origin}/success`,
cancel_url: `${req.headers.origin}/cancel`,
});
res.status(200).json({ id: session.id });
}
44. Use Next.js with Auth0
// pages/api/auth/[...auth0].js
import { handleAuth } from '@auth0/nextjs-auth0';
export default handleAuth();
45. Use Next.js with NextAuth.js
// pages/api/auth/[...nextauth].js
import NextAuth from 'next-auth';
export default NextAuth({
providers: [
{
name: 'Credentials',
credentials: {
username: { label: "Username", type: "text" },
password: { label: "Password", type: "password" }
},
authorize: async (credentials) => {
// Add logic to find the user
return null;
}
}
]
});
46. Use Next.js with Tailwind CSS
// postcss.config.js
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
};
47. Use Next.js with Material-UI
// pages/_app.js
import { ThemeProvider } from '@mui/material/styles';
import theme from '../src/theme';
function MyApp({ Component, pageProps }) {
return (
<ThemeProvider theme={theme}>
<Component {...pageProps} />
</ThemeProvider>
);
}
export default MyApp;
48. Use Next.js with Bootstrap
// pages/_app.js
import 'bootstrap/dist/css/bootstrap.min.css';
function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />;
}
export default MyApp;
49. Use Next.js with Ant Design
// pages/_app.js
import 'antd/dist/antd.css';
function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />;
}
export default MyApp
50. Use Next.js with Semantic UI
// pages/_app.js
import 'semantic-ui-css/semantic.min.css';
function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />;
}
export default MyApp;
51. Use Next.js with Emotion
// pages/_app.js
import { CacheProvider } from '@emotion/react';
import createEmotionCache from '../src/createEmotionCache';
const clientSideEmotionCache = createEmotionCache();
function MyApp({ Component, pageProps }) {
return (
<CacheProvider value={clientSideEmotionCache}>
<Component {...pageProps} />
</CacheProvider>
);
}
export default MyApp;
52. Use Next.js with Styled Components
// pages/_app.js
import { ThemeProvider } from 'styled-components';
import GlobalStyle from '../styles/globalStyles';
function MyApp({ Component, pageProps }) {
return (
<ThemeProvider theme={{}}>
<GlobalStyle />
<Component {...pageProps} />
</ThemeProvider>
);
}
export default MyApp;
53. Use Next.js with CSS-in-JS
// pages/index.js
import { css } from '@emotion/react';
function HomePage() {
return (
<div css={css`color: hotpink;`}>
<h1>Welcome to my homepage!</h1>
</div>
);
}
export default HomePage;
54. Use Next.js with PWA
// next.config.js
const withPWA = require('next-pwa');
module.exports = withPWA({
pwa: {
dest: 'public',
},
});
55. Use Next.js with AMP
// pages/index.js
import { useAmp } from 'next/amp';
const HomePage = () => {
const isAmp = useAmp();
return (
<div>
{isAmp ? <h1>AMP Page</h1> : <h1>Regular Page</h1>}
</div>
);
};
export const config = { amp: 'hybrid' };
export default HomePage;
56. Use Next.js with WebSockets
// pages/index.js
import { useEffect } from 'react';
function HomePage() {
useEffect(() => {
const socket = new WebSocket('ws://localhost:3000');
socket.onmessage = (event) => {
console.log(event.data);
};
}, []);
return <h1>WebSocket Example</h1>;
}
export default HomePage;
57. Use Next.js with GraphQL Client
// lib/apolloClient.js
import { ApolloClient, InMemoryCache } from '@apollo/client';
const client = new ApolloClient({
uri: 'https://api.example.com/graphql',
cache: new InMemoryCache(),
});
export default client;
58. Use Next.js with Redux Toolkit
// store.js
import { configureStore } from '@reduxjs/toolkit';
import rootReducer from './slices';
export const store = configureStore({
reducer: rootReducer,
});
59. Use Next.js with React Hook Form
// pages/index.js
import { useForm } from 'react-hook-form';
function HomePage() {
const { register, handleSubmit } = useForm();
const onSubmit = (data) => {
console.log(data);
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register('name')} />
<button type="submit">Submit</button>
</form>
);
}
export default HomePage;
60. Use Next.js with Formik
// pages/index.js
import { Formik, Form, Field } from 'formik';
function HomePage() {
return (
<Formik
initialValues={{ name: '' }}
onSubmit={(values) => {
console.log(values);
}}
>
<Form>
<Field name="name" />
<button type="submit">Submit</button>
</Form>
</Formik>
);
}
export default HomePage;
61. Use Next.js with React Query for Data Fetching
// pages/index.js
import { useQuery } from ' react-query';
function HomePage() {
const { data, error, isLoading } = useQuery('data', fetchData);
if (isLoading) return <div>Loading...</div>;
if (error) return <div>Error!</div>;
return <div>{data.message}</div>;
}
async function fetchData() {
const res = await fetch('/api/data');
return res.json();
}
62. Use Next.js with React Testing Library
// __tests__/index.test.js
import { render, screen } from '@testing-library/react';
import HomePage from '../pages/index';
test('renders homepage', () => {
render(<HomePage />);
const linkElement = screen.getByText(/Welcome to my homepage!/i);
expect(linkElement).toBeInTheDocument();
});
63. Use Next.js with Jest
// jest.config.js
module.exports = {
testEnvironment: 'jsdom',
setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
};
64. Use Next.js with Cypress
// cypress/integration/spec.js
describe('My First Test', () => {
it('Visits the homepage', () => {
cy.visit('/');
cy.contains('Welcome to my homepage!');
});
});
65. Use Next.js with Storybook
// .storybook/main.js
module.exports = {
stories: ['../pages/**/*.stories.@(js|jsx|ts|tsx)'],
addons: ['@storybook/addon-links', '@storybook/addon-essentials'],
};
66. Use Next.js with ESLint
// .eslintrc.json
{
"extends": "next/core-web-vitals"
}
67. Use Next.js with Prettier
// .prettierrc
{
"singleQuote": true,
"trailingComma": "all"
}
68. Use Next.js with TypeScript
// tsconfig.json
{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"esModuleInterop": true,
"module": "commonjs",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve"
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
"exclude": ["node_modules"]
}
69. Use Next.js with Custom Server
// server.js
const express = require('express');
const next = require('next');
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();
app.prepare().then(() => {
const server = express();
server.get('/custom', (req, res) => {
return app.render(req, res, '/custom', req.query);
});
server.all('*', (req, res) => {
return handle(req, res);
});
server.listen(3000, (err) => {
if (err) throw err;
console.log('> Ready on http://localhost:3000');
});
});
70. Use Next.js with Custom Routes
// next.config.js
module.exports = {
async redirects() {
return [
{
source: '/old-route',
destination: '/new-route',
permanent: true,
},
];
},
};
71. Use Next.js with Custom Headers
// next.config.js
module.exports = {
async headers() {
return [
{
source: '/(.*)',
headers: [
{
key: 'X-Custom-Header',
value: 'my-value',
},
],
},
];
},
};
72. Use Next.js with Custom Error Handling
// pages/_error.js
function Error({ statusCode }) {
return (
<p>
{statusCode
? `An error ${statusCode} occurred on server`
: 'An error occurred on client'}
</ pre>
);
}
Error.getInitialProps = async ({ res, err }) => {
const statusCode = res ? res.statusCode : err ? err.statusCode : 404;
return { statusCode };
};
export default Error;
73. Use Next.js with Custom Middleware
// middleware.js
export function middleware(req, res, next) {
console.log('Custom middleware executed');
next();
}
74. Use Next.js with Custom 404 Page
// pages/404.js
function Custom404() {
return <h1>404 - Page Not Found</h1>;
}
export default Custom404;
75. Use Next.js with Custom 500 Page
// pages/500.js
function Custom500() {
return <h1>500 - Server Error</h1>;
}
export default Custom500;
76. Use Next.js with Static File Serving
// public/image.png
// Place your static files in the public directory
77. Use Next.js with Custom Fonts
// pages/_document.js
import Document, { Html, Head, Main, NextScript } from 'next/document';
class MyDocument extends Document {
render() {
return (
<Html>
<Head>
<link rel="preload" href="/fonts/my-font.woff2" as="font" type="font/woff2" crossOrigin="anonymous" />
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
}
export default MyDocument;
78. Use Next.js with Custom API Routes
// pages/api/custom.js
export default function handler(req, res) {
res.status(200).json({ message: 'Custom API route' });
}
79. Use Next.js with Webpack Customization
// next.config.js
module.exports = {
webpack: (config) => {
config.module.rules.push({
test: /\.svg$/,
use: ['@svgr/webpack'],
});
return config;
},
};
80. Use Next.js with Custom Build Scripts
// package.json
"scripts": {
"build": "next build",
"start": "next start",
"dev": "next dev"
}
81. Use Next.js with Custom Environment Variables
// .env.local
NEXT_PUBLIC_API_URL=https://api.example.com
82. Use Next.js with Custom Error Handling Middleware
// middleware/errorHandler.js
export function errorHandler(err, req, res, next) {
console.error(err.stack);
res.status(500).send('Something broke!');
}
83. Use Next.js with Custom Logging Middleware
// middleware/logger.js
export function logger(req, res, next) {
console.log(`${req.method} ${req.url}`);
next();
}
84. Use Next.js with Custom Session Management
// lib/session.js
import { getSession } from 'next-auth/client';
export async function getServerSession(req) {
const session = await getSession({ req });
return session;
}
85. Use Next.js with Custom Authentication Middleware
// middleware/auth.js
import { getSession } from 'next-auth/client';
export async function auth(req, res, next) {
const session = await getSession({ req });
if (!session) {
return res.status(401).send('Unauthorized');
}
next();
}
86. Use Next.js with Custom Authorization Middleware
// middleware/authorization.js
export function authorization(req, res, next) {
if (!req.user || !req.user.isAdmin) {
return res.status(403).send('Forbidden');
}
next();
}
87. Use Next.js with Custom Rate Limiting Middleware
// middleware/rateLimit.js
import rateLimit from 'express-rate-limit';
export const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // limit each IP to 100 requests per windowMs
});
88. Use Next.js with Custom CORS Middleware
// middleware/cors.js
export function cors(req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
next();
}
89. Use Next.js with Custom Error Pages
// pages/_error.js
function Error({ statusCode }) {
return (
<p>
{statusCode
? `An error ${statusCode} occurred on server`
: 'An error occurred on client'}
</p>
);
}
Error.getInitialProps = async ({ res, err }) => {
const statusCode = res ? res.statusCode : err ? err.statusCode : 404;
return { statusCode };
};
export default Error;
90. Use Next.js with Custom 500 Error Page
// pages/500.js
function Custom500() {
return <h1>500 - Server Error</h1>;
}
export default Custom500;
91. Use Next.js with Custom 404 Error Page
// pages/404.js
function Custom404() {
return <h1>404 - Page Not Found</h1>;
}
export default Custom404;
92. Use Next.js with Custom API Error Handling
// pages/api/error.js
export default function handler(req, res) {
res.status(500).json({ error: 'Internal Server Error' });
}
93. Use Next.js with Custom API Rate Limiting
// pages/api/rateLimit.js
import rateLimit from 'express-rate-limit';
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // limit each IP to 100 requests per windowMs
});
export default function handler(req, res) {
limiter(req, res, () => {
res.status(200).json({ message: 'Rate limit applied' });
});
}
94. Use Next.js with Custom Middleware for Authentication
// middleware/auth.js
import { getSession } from 'next-auth/client';
export async function auth(req, res, next) {
const session = await getSession({ req });
if (!session) {
return res.status(401).send('Unauthorized');
}
next();
}
95. Use Next.js with Custom Middleware for Logging
// middleware/logger.js
export function logger(req, res, next) {
console.log(`${req.method} ${req.url}`);
next();
}
96. Use Next.js with Custom Middleware for CORS
// middleware/cors.js
export function cors(req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
next();
}
97. Use Next.js with Custom Middleware for Rate Limiting
// middleware/rateLimit.js
import rateLimit from 'express-rate-limit';
export const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // limit each IP to 100 requests per windowMs
});
98. Use Next.js with Custom Middleware for Session Management
// middleware/session.js
import { getSession } from 'next-auth/client';
export async function session(req, res, next) {
const session = await getSession({ req });
req.session = session;
next();
}
99. Use Next.js with Custom Middleware for Authorization
// middleware/authorization.js
export function authorization(req, res, next) {
if (!req.user || !req.user.isAdmin) {
return res.status(403).send('Forbidden');
}
next();
}
100. Use Next.js with Custom Middleware for Error Handling
// middleware/errorHandler.js
export function errorHandler(err, req, res, next) {
console.error(err.stack);
res.status(500).send('Something broke!');
}