|
| 1 | +--- |
| 2 | +title: Next.js - Integration |
| 3 | +--- |
| 4 | + |
| 5 | +# Next.js App Router |
| 6 | + |
| 7 | +<p class="description">This guide walks you through adding Toolpad Core to an existing Next.js app.</p> |
| 8 | + |
| 9 | +## Wrap your application with `AppProvider` |
| 10 | + |
| 11 | +In your root layout file (for example, `app/layout.tsx`), wrap your application with the `AppProvider`: |
| 12 | + |
| 13 | +```tsx title="app/layout.tsx" |
| 14 | +import { AppProvider } from '@toolpad/core/AppProvider'; |
| 15 | +import { AppRouterCacheProvider } from '@mui/material-nextjs/v14-appRouter'; |
| 16 | + |
| 17 | +export default function RootLayout({ children }: { children: React.ReactNode }) { |
| 18 | + return ( |
| 19 | + <AppRouterCacheProvider options={{ enableCssLayer: true }}> |
| 20 | + <AppProvider navigation={NAVIGATION} branding={BRANDING}> |
| 21 | + {children} |
| 22 | + </AppProvider> |
| 23 | + </AppRouterCacheProvider> |
| 24 | + ); |
| 25 | +} |
| 26 | +``` |
| 27 | + |
| 28 | +You can find details on the `AppProvider` props on the [AppProvider](/toolpad/core/react-app-provider/) page. |
| 29 | + |
| 30 | +:::info |
| 31 | +The `AppRouterCacheProvider` component is not required to use Toolpad Core, but it's recommended to use it to ensure that the styles are appended to the `<head>` and not rendering in the `<body>`. |
| 32 | + |
| 33 | +See the [Material UI Next.js integration docs](https://mui.com/material-ui/integrations/nextjs/) for more details. |
| 34 | +::: |
| 35 | + |
| 36 | +## Create a dashboard layout |
| 37 | + |
| 38 | +Create a layout file for your dashboard pages (for example, `app/(dashboard)/layout.tsx`): |
| 39 | + |
| 40 | +```tsx title="app/(dashboard)/layout.tsx" |
| 41 | +import * as React from 'react'; |
| 42 | +import { DashboardLayout } from '@toolpad/core/DashboardLayout'; |
| 43 | +import { PageContainer } from '@toolpad/core/PageContainer'; |
| 44 | + |
| 45 | +export default function DashboardPagesLayout(props: { children: React.ReactNode }) { |
| 46 | + return ( |
| 47 | + <DashboardLayout> |
| 48 | + <PageContainer>{props.children}</PageContainer> |
| 49 | + </DashboardLayout> |
| 50 | + ); |
| 51 | +} |
| 52 | +``` |
| 53 | + |
| 54 | +The [`DashboardLayout`](/toolpad/core/react-dashboard-layout/) component provides a consistent layout for your dashboard pages, including a sidebar, navigation, and header. The [`PageContainer`](/toolpad/core/react-page-container/) component is used to wrap the page content, and provides breadcrumbs for navigation. |
| 55 | + |
| 56 | +## Create a dashboard page |
| 57 | + |
| 58 | +Now you can create pages within your dashboard. For example, a home page (`app/(dashboard)/page.tsx`): |
| 59 | + |
| 60 | +```tsx title="app/(dashboard)/page.tsx" |
| 61 | +import * as React from 'react'; |
| 62 | +import Typography from '@mui/material/Typography'; |
| 63 | + |
| 64 | +export default function Page() { |
| 65 | + return <Typography>Welcome to a page in the dashboard!</Typography>; |
| 66 | +} |
| 67 | +``` |
| 68 | + |
| 69 | +That's it! You have now integrated Toolpad Core into your Next.js app. |
| 70 | + |
| 71 | +## (Optional) Add a second page |
| 72 | + |
| 73 | +Create a new page in the dashboard, for example, `app/(dashboard)/orders/page.tsx`: |
| 74 | + |
| 75 | +```tsx title="app/(dashboard)/orders/page.tsx" |
| 76 | +import * as React from 'react'; |
| 77 | +import Typography from '@mui/material/Typography'; |
| 78 | + |
| 79 | +export default function OrdersPage() { |
| 80 | + return <Typography>Welcome to the orders page!</Typography>; |
| 81 | +} |
| 82 | +``` |
| 83 | + |
| 84 | +To add this page to the navigation, add it to the `NAVIGATION` variable: |
| 85 | + |
| 86 | +```ts title="app/layout.tsx" |
| 87 | +export const NAVIGATION = [ |
| 88 | + // ... |
| 89 | + { |
| 90 | + segment: 'orders', |
| 91 | + title: 'Orders', |
| 92 | + icon: <ShoppingCartIcon />, |
| 93 | + }, |
| 94 | + // ... |
| 95 | +]; |
| 96 | +``` |
| 97 | + |
| 98 | +## (Optional) Set up authentication |
| 99 | + |
| 100 | +If you want to add authentication, you can use Auth.js with Toolpad Core. Here's an example setup: |
| 101 | + |
| 102 | +### Install the dependencies |
| 103 | + |
| 104 | +```bash |
| 105 | +npm install next-auth@beta |
| 106 | +``` |
| 107 | + |
| 108 | +### Create an `auth.ts` file |
| 109 | + |
| 110 | +```ts title="auth.ts" |
| 111 | +import NextAuth from 'next-auth'; |
| 112 | +import GitHub from 'next-auth/providers/github'; |
| 113 | +import type { Provider } from 'next-auth/providers'; |
| 114 | + |
| 115 | +const providers: Provider[] = [ |
| 116 | + GitHub({ |
| 117 | + clientId: process.env.GITHUB_CLIENT_ID, |
| 118 | + clientSecret: process.env.GITHUB_CLIENT_SECRET, |
| 119 | + }), |
| 120 | +]; |
| 121 | + |
| 122 | +export const providerMap = providers.map((provider) => { |
| 123 | + if (typeof provider === 'function') { |
| 124 | + const providerData = provider(); |
| 125 | + return { id: providerData.id, name: providerData.name }; |
| 126 | + } |
| 127 | + return { id: provider.id, name: provider.name }; |
| 128 | +}); |
| 129 | + |
| 130 | +export const { handlers, auth, signIn, signOut } = NextAuth({ |
| 131 | + providers, |
| 132 | + secret: process.env.AUTH_SECRET, |
| 133 | + pages: { |
| 134 | + signIn: '/auth/signin', |
| 135 | + }, |
| 136 | + callbacks: { |
| 137 | + authorized({ auth: session, request: { nextUrl } }) { |
| 138 | + const isLoggedIn = !!session?.user; |
| 139 | + const isPublicPage = nextUrl.pathname.startsWith('/public'); |
| 140 | + |
| 141 | + if (isPublicPage || isLoggedIn) { |
| 142 | + return true; |
| 143 | + } |
| 144 | + |
| 145 | + return false; // Redirect unauthenticated users to login page |
| 146 | + }, |
| 147 | + }, |
| 148 | +}); |
| 149 | +``` |
| 150 | + |
| 151 | +### Create a sign-in page |
| 152 | + |
| 153 | +Use the `SignInPage` component to add a sign-in page to your app. For example, `app/auth/signin/page.tsx`: |
| 154 | + |
| 155 | +```tsx title="app/auth/signin/page.tsx" |
| 156 | +import * as React from 'react'; |
| 157 | +import { SignInPage, type AuthProvider } from '@toolpad/core/SignInPage'; |
| 158 | +import { AuthError } from 'next-auth'; |
| 159 | +import { providerMap, signIn } from '../../../auth'; |
| 160 | + |
| 161 | +export default function SignIn() { |
| 162 | + return ( |
| 163 | + <SignInPage |
| 164 | + providers={providerMap} |
| 165 | + signIn={async ( |
| 166 | + provider: AuthProvider, |
| 167 | + formData: FormData, |
| 168 | + callbackUrl?: string, |
| 169 | + ) => { |
| 170 | + 'use server'; |
| 171 | + try { |
| 172 | + return await signIn(provider.id, { |
| 173 | + redirectTo: callbackUrl ?? '/', |
| 174 | + }); |
| 175 | + } catch (error) { |
| 176 | + // The desired flow for successful sign in in all cases |
| 177 | + // and unsuccessful sign in for OAuth providers will cause a `redirect`, |
| 178 | + // and `redirect` is a throwing function, so we need to re-throw |
| 179 | + // to allow the redirect to happen |
| 180 | + // Source: https://github.com/vercel/next.js/issues/49298#issuecomment-1542055642 |
| 181 | + // Detect a `NEXT_REDIRECT` error and re-throw it |
| 182 | + if (error instanceof Error && error.message === 'NEXT_REDIRECT') { |
| 183 | + throw error; |
| 184 | + } |
| 185 | + // Handle Auth.js errors |
| 186 | + if (error instanceof AuthError) { |
| 187 | + return { |
| 188 | + error: error.message, |
| 189 | + type: error.type, |
| 190 | + }; |
| 191 | + } |
| 192 | + // An error boundary must exist to handle unknown errors |
| 193 | + return { |
| 194 | + error: 'Something went wrong.', |
| 195 | + type: 'UnknownError', |
| 196 | + }; |
| 197 | + } |
| 198 | + }} |
| 199 | + /> |
| 200 | + ); |
| 201 | +} |
| 202 | +``` |
| 203 | + |
| 204 | +### Create a route handler for sign-in |
| 205 | + |
| 206 | +`next-auth` requires a route handler for sign-in. Create a file `app/api/auth/[...nextauth]/route.ts`: |
| 207 | + |
| 208 | +```ts title="app/api/auth/[...nextauth]/route.ts" |
| 209 | +import { handlers } from '../../../../auth'; |
| 210 | + |
| 211 | +export const { GET, POST } = handlers; |
| 212 | +``` |
| 213 | + |
| 214 | +### Add a middleware |
| 215 | + |
| 216 | +Add a middleware to your app to protect your dashboard pages: |
| 217 | + |
| 218 | +```ts title="middleware.ts" |
| 219 | +export { auth as middleware } from './auth'; |
| 220 | + |
| 221 | +export const config = { |
| 222 | + // https://nextjs.org/docs/app/building-your-application/routing/middleware#matcher |
| 223 | + matcher: ['/((?!api|_next/static|_next/image|.*\\.png$).*)'], |
| 224 | +}; |
| 225 | +``` |
| 226 | + |
| 227 | +That's it! You now have Toolpad Core integrated into your Next.js App Router app with authentication setup: |
| 228 | + |
| 229 | +{{"component": "modules/components/DocsImage.tsx", "src": "/static/toolpad/docs/core/integration-nextjs-app.png", "srcDark": "/static/toolpad/docs/core/integration-nextjs-app-dark.png", "alt": "Next.js App Router with Toolpad Core", "caption": "Next.js App Router with Toolpad Core", "zoom": true, "aspectRatio": "1.428" }} |
| 230 | + |
| 231 | +:::info |
| 232 | +For a full working example with authentication included, see the [Toolpad Core Next.js App with Auth.js example](https://github.com/mui/toolpad/tree/master/examples/core/auth-nextjs/) |
| 233 | +::: |
0 commit comments