#nextjs
1 messages · Page 1 of 1 (latest)
In Next.js, you can create API routes to handle server-side operations like accessing a database. Any file inside the pages/api folder is treated as an API endpoint instead of a page. They are server-side only bundles and won't increase your client-side bundle size.
Here's an example of a basic API route that returns a JSON response:
import type { NextApiRequest, NextApiResponse } from 'next'
type ResponseData = {
message: string
}
export default function handler(
req: NextApiRequest,
res: NextApiResponse<ResponseData>
) {
res.status(200).json({ message: 'Hello from Next.js!' })
}
(Source: Next.js Docs (https://nextjs.org/docs/pages/building-your-application/routing/api-routes))
API routes provide built-in middlewares which parse the incoming request (req). Those middlewares include req.cookies, req.query, and req.body. There's also support for additional middlewares.
However, if you are using the App Router, you can use Server Components or Route Handlers instead of API Routes.
Remember, the choice between creating an API route or a function to access your database depends on your specific use case and the architecture of your application.
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
@flat kite kapa.ai is still learning and improving, please let us know how it did by reacting below
@terse gate how to create server components or route handlers in app router?
Let me check the knowledge base for you. One moment! :books:
In Next.js version 13, a new App Router was introduced which supports shared layouts, nested routing, loading states, error handling, and more. The App Router works in a new directory named app, which works alongside the pages directory. By default, components inside app are React Server Components.
Here's how you can create Server Components and Route Handlers:
Server Components:
Server Components are files in the app directory that end with .server.tsx. They can fetch data and render HTML on the server, which is then sent to the client.
Route Handlers:
Route Handlers allow you to create custom request handlers for a given route using the Web Request and Response APIs. A route.ts file can export an async function named by the HTTP verbs: GET, HEAD, OPTIONS, POST, PUT, DELETE, and PATCH.
Here's an example of a Route Handler:
export async function GET(request: Request) {
// Your custom logic here
}
And here's an example with cookies:
import { cookies } from 'next/headers';
export async function GET(request: Request) {
const cookieStore = cookies();
const token = cookieStore.get('token');
return new Response('Hello, Next.js!', {
status: 200,
headers: { 'Set-Cookie': `token=${token}` },
});
}
These functions can then be wrapped and abstracted to create helpers / reusable logic for your custom route logic. Other server functions, like cookies and headers, can be used inside Route Handlers – along with any Web APIs these abstractions are built upon. This allows for code to be shared between Server Components and Route Handlers.
For more information, you can check out the Next.js documentation on Routing (https://nextjs.org/docs/app/building-your-application/routing) and Custom Route Handlers (https://nextjs.org/blog/next-13-2#custom-route-handlers).
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
@flat kite kapa.ai is still learning and improving, please let us know how it did by reacting below
@terse gate best way to create a username validation in create user form using nextjs 14
Let me check the knowledge base for you. One moment! :books:
In Next.js, you can use HTML validation for basic form validation. For more advanced server-side validation, you can use a schema validation library like zod (https://zod.dev/) to validate the structure of the parsed form data.
Here's an example of how you can use zod for username validation in a form:
import type { NextApiRequest, NextApiResponse } from 'next'
import { z } from 'zod'
const schema = z.object({
username: z.string().min(1).max(20),
// other fields...
})
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
const parsed = schema.parse(req.body)
// ...
}
In this example, z.string().min(1).max(20) ensures that the username is a string with a minimum length of 1 and a maximum length of 20. You can adjust these values as per your requirements.
You can also add more complex validation rules. For example, if you want to ensure that the username only contains alphanumeric characters, you can use a regular expression:
username: z.string().regex(/^[a-z0-9]+$/i),
This will ensure that the username only contains letters and numbers.
Remember to handle the errors appropriately and return a meaningful error message to the client if the validation fails.
For more information, you can check out the Next.js documentation on Forms and Mutations (https://nextjs.org/docs/pages/building-your-application/data-fetching/forms-and-mutations).
(Source: Next.js Docs (https://nextjs.org/docs/pages/building-your-application/data-fetching/forms-and-mutations))
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
@flat kite kapa.ai is still learning and improving, please let us know how it did by reacting below
@terse gate i want to create a global function to validate the username everytime i create or update the user in nextjs 14 app router
Let me check the knowledge base for you. One moment! :books:
In Next.js 14 with App Router, you can create a utility function to validate the username. This function can be used in multiple places in your application, such as in your Route Handlers for creating or updating a user.
Here's an example of how you can create a utility function for username validation using zod:
// lib/validateUsername.ts
import { z } from 'zod';
const schema = z.object({
username: z.string().min(1).max(20).regex(/^[a-z0-9]+$/i),
});
export function validateUsername(username: string) {
try {
schema.parse({ username });
return true;
} catch (error) {
return false;
}
}
In this example, validateUsername is a function that takes a username as a parameter and returns true if the username is valid and false otherwise.
You can then use this function in your Route Handlers:
// app/users/create.route.ts
import { validateUsername } from '../../lib/validateUsername';
export async function POST(request: Request) {
const { username } = await request.json();
if (!validateUsername(username)) {
return new Response('Invalid username', { status: 400 });
}
// ... create user ...
}
In this example, the POST function is a Route Handler for creating a user. It uses the validateUsername function to validate the username before creating the user. If the username is invalid, it returns a 400 response with an error message.
Remember to adjust the validation rules in the validateUsername function as per your requirements.
For more information, you can check out the Next.js documentation on Routing (https://nextjs.org/docs/app/building-your-application/routing) and Custom Route Handlers (https://nextjs.org/blog/next-13-2#custom-route-handlers).
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
@flat kite kapa.ai is still learning and improving, please let us know how it did by reacting below
how to organized it? i want it to be organized in my lib folder.
@terse gate how to organized it? i want it to be organized in my lib folder.
Let me check the knowledge base for you. One moment! :books:
In Next.js, you can organize your utility functions in the lib directory. This is a common practice and it helps to keep your codebase clean and organized. Here's how you can do it:
-
Create a
libdirectory in the root of your project or inside thesrcdirectory if you're using thesrcdirectory structure. -
Inside the
libdirectory, create a new file for each utility function. For example, you can create avalidateUsername.tsfile for thevalidateUsernamefunction:
// lib/validateUsername.ts
import { z } from 'zod';
const schema = z.object({
username: z.string().min(1).max(20).regex(/^[a-z0-9]+$/i),
});
export function validateUsername(username: string) {
try {
schema.parse({ username });
return true;
} catch (error) {
return false;
}
}
- You can then import and use these utility functions in your Route Handlers or anywhere else in your application:
// app/users/create.route.ts
import { validateUsername } from '../../lib/validateUsername';
export async function POST(request: Request) {
const { username } = await request.json();
if (!validateUsername(username)) {
return new Response('Invalid username', { status: 400 });
}
// ... create user ...
}
This way, your utility functions are organized in a separate lib directory and can be easily reused across your application.
For more information, you can check out the Next.js documentation on Project Organization and File Colocation (https://nextjs.org/docs/app/building-your-application/routing/colocation).
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
@flat kite kapa.ai is still learning and improving, please let us know how it did by reacting below
can you give me an example of server-actions in nextjs 14
@terse gate can you give me an example of server-actions in nextjs 14
Let me check the knowledge base for you. One moment! :books: