new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

Next.js · Guides · all subjects

authentication/pages-router

5 notes, read out of this brain and free to use. Each one was extracted from a source and is re-checked against its exam.

Reading nonce in Pages Router with getServerSideProps

In Next.js Pages Router, provide the nonce using getServerSideProps: ```tsx import Script from 'next/script' import type { GetServerSideProps } from 'next' export default function Page({ nonce }) { return ( <Script src="https://www.googletagmanager.com/gtag/js" strategy="afterInteractive" nonce={nonce} /> ) } export const getServerSideProps: GetServerSideProps = async ({ req }) => { const nonce = req.headers['x-nonce'] return { props: { nonce } } } ```

Nonce in Pages Router _document.tsx

In Pages Router, access nonce in _document.tsx: ```tsx import Document, { Html, Head, Main, NextScript, DocumentContext, DocumentInitialProps } from 'next/document' interface ExtendedDocumentProps extends DocumentInitialProps { nonce?: string } class MyDocument extends Document<ExtendedDocumentProps> { static async getInitialProps(ctx: DocumentContext): Promise<ExtendedDocumentProps> { const initialProps = await Document.getInitialProps(ctx) const nonce = ctx.req?.headers?.['x-nonce'] as string | undefined return { ...initialProps, nonce } } render() { const { nonce } = this.props return ( <Html lang="en"> <Head nonce={nonce} /> <body> <Main /> <NextScript nonce={nonce} /> </body> </Html> ) } } export default MyDocument ```

Pages Router login form example

import { FormEvent } from 'react' import { useRouter } from 'next/router' export default function LoginPage() { const router = useRouter() async function handleSubmit(event: FormEvent<HTMLFormElement>) { event.preventDefault() const formData = new FormData(event.currentTarget) const email = formData.get('email') const password = formData.get('password') const response = await fetch('/api/auth/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email, password }), }) if (response.ok) { router.push('/profile') } else { // Handle errors } } return ( <form onSubmit={handleSubmit}> <input type="email" name="email" placeholder="Email" required /> <input type="password" name="password" placeholder="Password" required /> <button type="submit">Login</button> </form> ) }

Pages Router API route for login

import type { NextApiRequest, NextApiResponse } from 'next' import { signIn } from '@/auth' export default async function handler( req: NextApiRequest, res: NextApiResponse ) { try { const { email, password } = req.body await signIn('credentials', { email, password }) res.status(200).json({ success: true }) } catch (error) { if (error.type === 'CredentialsSignin') { res.status(401).json({ error: 'Invalid credentials.' }) } else { res.status(500).json({ error: 'Something went wrong.' }) } } }

Pages Router API route with authentication check

import { NextApiRequest, NextApiResponse } from 'next' export default async function handler( req: NextApiRequest, res: NextApiResponse ) { const session = await getSession(req) if (!session) { res.status(401).json({ error: 'User is not authenticated', }) return } if (session.user.role !== 'admin') { res.status(401).json({ error: 'Unauthorized access: User does not have admin privileges.', }) return } // Proceed with the route for authorized users }

Give your agent this brain