DEV Community

Cover image for 5 Things AI Can't Do, Even in • Next.js
DevUnionX
DevUnionX

Posted on

5 Things AI Can't Do, Even in • Next.js

This report examines limitations AI-assisted tools encounter in Next.js development process. Five main topics address technical nuances specific to Next.js infrastructure: component and page semantics including differences between SSR, SSG, and ISR, data fetching and caching covering getServerSideProps, getStaticProps, App Router fetch, and cache headers, routing and dynamic routes with i18n and Middleware edge cases, performance and build toolchain addressing image optimization, ISR, server components, and packaging, and finally security and deployment examining Edge versus Server environments, secret keys, and header management.

Each section provides technical detail, concrete error scenarios AI encounters explained through real-world examples from GitHub issues and blog posts. For instance in data fetching, getStaticProps usage is emphasized because this function runs only on server and doesn't get included in client bundle, meaning secret keys or private request information don't leak from here. But AI assistants sometimes cannot see this distinction and might transfer problematic data to client side. In performance section, Next.js Image component becomes important. AI frequently makes simple operations with standard img tag, whereas Next.js Image serves visuals in WebP or AVIF format appropriate to screen size.

Table noting differences between AI-generated and human-written code regarding correctness, accessibility, maintainability, package size, and deployment security shows AI-sourced code generally contains more errors. Ultimately, human supervision remains indispensable in Next.js-specific advanced topics. For this study, primarily Next.js official documents and latest release notes were reviewed. Then Next.js community resources including GitHub Issues and StackOverflow, developer blogs, and case studies were examined, particularly ISR errors and i18n topics. Accessibility guides with WCAG and security standards were compared against Next.js examples. Research revealing AI code assistant limitations was also reviewed. All this data was gathered under five distinct topics enriched with technical explanations, code examples, error scenarios, and solution recommendations.

Next.js serves pages through various pre-rendering methods. SSR or Server-Side Rendering runs on each request. SSG or Static Site Generation creates page at build time. ISR or Incremental Static Regeneration caches static page and renews at specific intervals. Conscious decision should be made about which method to use. For pages requiring user-specific data or authorization, SSR with getServerSideProps should be preferred. Sensitive information should never be added to React components through getStaticProps because this function runs only on server and sends its output to client side. AI assistants sometimes skip this distinction.

For example assume someone uses API key in getStaticProps. Lock warning, secret key should not leak to client. Export async function getStaticProps. Const apiKey equals process.env.SECRET_API_KEY. Const res equals await fetch showing API example URL with key parameter. Const data equals await res.json. Return props with data. In above code SECRET_API_KEY doesn't go to browser because used inside getStaticProps, only processes server side. But AI sometimes might not comply with this rule and cause security vulnerability by adding API key directly to client component.

AI assistants generally miss optimal choice between SSR and SSG. For instance can lower performance by using unnecessary SSR when static cache is possible, or conversely can use static methods to fetch dynamic data. Another error is making wrong ISR settings or not using at all. According to Next.js documents, if a route contains revalidate 0 or no-store in any fetch call, route gets rendered dynamically. If such details are overlooked in AI assistant code, ISR's purpose can break. Wrong example with if revalidate not used, data updates on every request and cache becomes ineffective. Export async function getStaticProps with const res equals await fetch API posts URL with next revalidate false. Const posts equals await res.json. Return props with posts.

In above code revalidate false is specified but static file still gets created in background. Correct usage is making intervals with revalidate number form. AI generally skips these nuances and considers page either static or completely dynamic. Example showing scenario wanting to update page on every request with SSR. SSR example with getServerSideProps runs on every request. Export async function getServerSideProps with context parameter. Const res equals await fetch API data URL with lang equals context.locale. Const data equals await res.json. Return props with data. Export default function Page with data parameter. Return div with data.content. getServerSideProps runs server side and can get request-specific values like locale information.

In this example, getServerSideProps usage suits situations requiring request-time information like locale or authorization. If AI assistant misinterprets this concept, might try getting dynamic data with getStaticProps and encounter wrong results. Developer strategies: correct pre-rendering strategy should be selected according to page's data requirement. Check in code from AI that getStaticProps, getServerSideProps, or getStaticPaths are used correctly. Sensitive data should never be transferred to client. If using ISR, ensure revalidate times are appropriate. If page will be statically created, pages versus app folder configurations should be reviewed. Data fetching logic at Page versus Component level should be clarified according to application needs, example codes AI suggested should be supervised according to these rules.

Next.js provides both Pages Router with getStaticProps, getServerSideProps, getStaticPaths and App Router with fetch inside server components for data fetching. Each method's caching behavior differs. Data fetched with getStaticProps gets cached at build time or in ISR mode, getServerSideProps renews data on every request. AI assistants sometimes select wrong function, for instance can lower performance by fetching simple content with SSR. Additionally Next.js fetch API extended features like next revalidate 60 get mostly bypassed.

For example data fetching in page using App Router. In app/users/page.tsx export default async function UsersPage. Const res equals await fetch API users URL with next revalidate 60 for caching data with revalidate setting. Const users equals await res.json. Return ul with users.map showing li key equals u.id with u.name. AI mostly skips this next revalidate 60 setting. In above code we enabled data renewal every 60 seconds by adding next revalidate 60. If AI assistant doesn't add this setting, page either renews on every request as default or can serve stale data without ever renewing.

As specified in Next.js documents, if revalidate 0 or no-store is used in a fetch request, route becomes dynamic. On other hand when giving caching strategy, Next.js built-in cache should be preferred instead of libraries like React Query. AI generally avoids using fetch inside getServerSideProps and setting cache headers. Failure modes: AI-assisted codes can overlook difference between getStaticProps and getServerSideProps. For instance trying to use data like context.params inside getStaticProps gives error. Not setting correct Cache-Control headers for caching or not using Next.js revalidate features is frequently seen. Example of making wrong cache settings follows.

Export async function getStaticProps. Const res equals await fetch API posts URL with wrong can be skipped by AI, next revalidate 0 causes page to be recreated on every request. Const posts equals await res.json. Return props with posts. In above wrong usage, revalidate 0 means data renews on every request without caching. Whereas generally few seconds of cache would be sufficient. Additionally AI mostly doesn't benefit from context information belonging to getStaticProps like query or headers, leading to error in situations requiring conversion to SSR. For instance when user wants to read browser language from Accept-Language header and change content, getStaticProps not being able to do this becomes a problem.

Example showing cached page using ISR. Export async function getStaticProps. Const res equals await fetch API products URL with next revalidate 300 for recaching every 5 minutes. Const products equals await res.json. Return props with products. Export default function ProductsPage with products parameter. Return div with products.map showing p key equals p.id with p.name. getStaticProps runs on server, cache set with next.revalidate. If AI code skipped revalidate value, page stays static and might not stay current. Similarly if correct cache options aren't put in fetch queries, Next.js built-in client or server cache might not activate.

Developer strategies: optimize code following Next.js caching guide, for example using next revalidate in fetch. Data renewal settings AI skipped should be manually added. For cache control, Cache-Control headers in HTTP responses should be validated with Vercel or browser tools. To test ISR and SSG structures, cache behavior should be observed in production-like scenario by running next build and next start. Additionally avoid sending unnecessary data to client. For instance if data fetched with getServerSideProps goes to client in props, pay attention to sensitive fields. AI code must definitely go through manual review and test processes.

Next.js has powerful routing system supporting file-based routes or Route Segments, dynamic segments like bracket id.js and bracket dot dot dot catchAll, subdirectories, and internationalization i18n. Next.js additionally uses middleware for preprocessing incoming requests and dynamizing routes. AI can make errors especially in i18n and getStaticPaths combinations. For instance for multilingual blog page, every language variant needs to be returned inside getStaticPaths. According to Next.js guide, each localization combination should be specified separately.

In pages/blog/bracket slug.js export const getStaticPaths equals with locales parameter. Return paths array containing params slug merhaba with locale tr, params slug hello with locale en-US, and fallback true. Above specified separate slug path for each language. AI generally skips this step and specifies only paths belonging to default language, resulting in 404 error in other languages. When getStaticPaths is used, if a route outside what you specified is requested, behavior depends on fallback option. AI tools sometimes skip difference between fallback true versus false or blocking, leading to unexpected user experiences.

In a GitHub discussion, how to manage fallback mode between i18n and dynamic routes was explained. For instance during language switches, in a request outside getStaticPaths scope, page is expected to load with fallback true, but if this gets forgotten in AI code, empty page or error can occur. Next.js can redirect routes or add headers using middleware. AI code can struggle understanding middleware logic. For instance instead of defining middleware for a path requiring authentication, might put redirect code in page component. Additionally AI generally doesn't consider Edge and Server environment difference. For instance if using Vercel Edge Functions, special methods are needed instead of process.env.

Developer strategies: in i18n and dynamic routes, directives in Next.js documentation should be followed. Ensure in code from AI that locales and locale settings are complete. Pay attention that paths getStaticPaths returns are complete for every variant. If middleware usage needed, example configurations like JWT validation should be checked. Review next.config.js settings like route groups and routing with redirects and rewrites in code AI added. Test that page handles appropriately with notFound or redirect in error situations like wrong parameter.

Next.js offers performance-focused optimizations: Image component, automatic code splitting, ISR, server components in app folder, and advanced configuration with next.config.js. AI generally skips some of these features. For instance using classic img instead of Image usage makes page load heavier. According to Next.js documentation, Image tag serves visuals in appropriate size WebP or AVIF according to device size. Import Image from next/image. Export default function Avatar. Return Image source /avatar.png width 200 height 200 alt Avatar Image with priority. Image component uses automatically optimized images.

In AI-assisted code, generally with img given fixed size, page shift and unnecessary package load emerge. Additionally in large projects creating many pages, AI can create confusion in ISR, dynamic render, and static export decisions. For instance as error might skip flags like export const dynamic equals force-static or export const dynamicParams equals false. With Next.js 13 plus server components RSC were introduced. AI codes mostly cannot see use client rule to push components to client side. This causes unnecessary JavaScript to be loaded to client. If use client deficiency in code snippet is overlooked, RSC benefit gets wasted.

In enterprise projects package size directly affects performance. AI outputs generally come with broad imports and repeated code. For instance importing entire third-party library and including even unused functions is typical error. According to StackOverflow source, to reduce this situation, code splitting and partial import are needed. AI code generally doesn't consider these recommendations. For instance imports entire lodash library. Wrong example with imported all of lodash. Import underscore from lodash. Const arr equals underscore.map array with lambda. Good example importing only needed function. Import map from lodash/map. Const arr equals map array with lambda.

AI code generally bloats package size, negatively affecting load times and user experience. Developer strategies: apply official recommendations for performance. Check in AI code for Image usage and use client settings for components requiring dynamism. Review code splitting strategies with dynamic import and React.lazy and compression steps. Review experimental settings and optimization options in Next.js configuration. With bundle analysis tools check whether AI outputs carry unnecessary dependencies. If needed, manually add performance improvements to part AI wrote.

The following table presents general comparison in Next.js context between AI generation and human generation. Correctness low with wrong redirects, stale data, and missing revalidation errors versus High with SSR and SSG decisions and fetch settings proper. Accessibility medium, generally mixes page semantics with head meta forgotten versus Good with tags like lang and hreflang complete. Maintainability low with automatic code repetition and incomprehensible data flow versus High with modular structure and comment lines added.

Package Size high with unnecessary imports and packages like entire lodash included versus Low with only needed modules and code splitting used. Deployment Security low with environment variables used in wrong place and security update not done versus High with secret values kept on server and updates tracked. The mermaid flowchart summarizes Next.js development process. At start required data fetching method and page type determined. Code from AI gets checked with correct SSR, SSG, ISR options and i18n settings. If needed additions made to AI code like locale parameter and revalidate times. Next step reviews Image usage, code splitting, and other performance optimizations.

Security steps checked including environment variable usage and security patches. At very end code approved with package analysis and tests. When deficiency detected, process returns to start with manual correction done. Flowchart shows: Requirements including page data, routing, performance. Get Next.js code from AI. Decision whether page concept and data method determined. If no add appropriate fetch and SSR/SSG settings to AI code and return. If yes decision whether dynamic route and i18n needs exist. If yes do i18n and getStaticPaths/locale check and return. If no decision whether image optimization done. If incomplete return. If complete decision security whether secret data in correct place. If incomplete return. If complete bundle and performance analysis. Code review and final approval with tests.

In Next.js applications, security starts especially with well-drawn server to client boundary. Secret keys that should be kept server side should never go to client. Environment variables without NEXT_PUBLIC prefix are visible only on server. AI assistants often miss this rule. For instance might place secret API key inside server component. Update management and CVE announcement tracking is needed. For instance a critical security vulnerability in React Server Components protocol CVE-2025-66478 affected Next.js 15 to 16 versions with remote code execution risk. Only upgrading Next.js solves this problem. Closing such risk with AI code suggestions isn't possible.

Vercel Edge and Server environments bring different requirements. For instance in Edge Functions, fetch usage, Node APIs, or long-running operations are limited. AI might suggest configurations like process.env not used in Edge environment giving error. Middleware and header management are also critical. In Next.js 13 security headers or custom headers are added inside next.config.js. AI generally doesn't create these configuration files.

Example showing secure redirect middleware. In middleware.js import NextResponse from next/server. Export function middleware with request parameter. Const token equals request.cookies.get auth_token. If no token redirect to login with NextResponse.redirect new URL /login and request.url. Return NextResponse.next. Use this middleware on all pages requiring authentication. AI assistant might not recognize standard libraries like Auth.js and can make wrong redirect or open redirect error. Environment variable management is also one of topics where AI causes problems. Next.js documentation notes variables without NEXT_PUBLIC will be stored on server.

AI code might mistakenly try using all variables in frontend. Additionally separating important operations from client using server components might be needed. Before deployment, attention should be paid to security scans in CI/CD pipelines like npm audit, all versions should be updated with latest security patch. Developer strategies: apply Next.js security guides. In server components use only server environment variables like process.env.SECRET, don't pass encrypted key or secret information to client. Carefully examine middleware or redirect codes AI added. Take precautions against open redirects and CSRF and XSS attacks. When managing environment variables in Vercel Panel or .env file, ensure NEXT_PUBLIC prefix rules are followed. Finally choose structure appropriate to environment Edge versus Server and validate deployment security with manual tests before deployment.

Top comments (0)