title: Page and Route Management in Nuxt Kit
date: 2024/9/17
updated: 2024/9/17
author: cmdragon
excerpt:
Abstract: This article introduces the advanced features of page and route management in Nuxt Kit , including extendPages custom page routing , extendRouteRules define complex routing logic and addRouteMiddleware registration routing middleware. With these features, developers can flexibly add and modify routes, set caching, redirection, etc., and implement middleware processing such as access control to improve the development efficiency and maintainability of Web applications.
categories:
- front-end development
tags:
- Nuxt
- routing (in computer networks)
- managerial
- middleware
- (computing) cache
- redirects
- dynamic (science)
scanningtwo-dimensional barcodeFollow or microsoft search:Programming Intelligence Front-End to Full-Stack Communication and Growth
Route management is a core feature when building modern web applications. A range of powerful and flexible tools are provided to help you create and manage pages and their routing.
1. extendPages
: Customized page routing
1.1 Functional description
extendPages
Allows you to add, remove or modify automatically generated routes as needed. By default, Nuxt automatically generates routes according to thepages
The structure of the files in the directory generates routes, but sometimes you may need more complex routing logic.
1.2 Type signatures
function extendPages(callback: (pages: NuxtPage[]) => void): void
parameters
-
callback: A function that takes a
NuxtPage
array as a parameter, which you can modify.
1.3 NuxtPage
connector
type NuxtPage = {
name?: string; // optional name
path: string; // Route path
file?: string; // Path to the associated file.
meta?: Record<string, any>; // The routing metadata.
alias?: string[] | string; // Aliases
redirect?: RouteLocationRaw; // The redirect configuration.
children?: NuxtPage[]; // Child routes.
}
1.4 Examples
Here's how to useextendPages
Complete example of adding a new route:
//
import { createResolver, defineNuxtModule, extendPages } from '@nuxt/kit';
export default defineNuxtModule({
setup(options) {
const resolver = createResolver();
extendPages((pages) => {
({
name: 'custom-preview',
path: '/custom-preview',
file: ('runtime/'), // Points to the component file
});
});
}
});
1.5 Practical application scenarios
-
dynamic routing: If there's an absence
pages
directory for dynamic routes (such as user-configured routes), you can use this feature to add these routes. - Modifying the Default Route: Sometimes you may want to change or remove the default route to meet specific needs.
2. extendRouteRules
: Define complex routing logic
2.1 Functional description
extendRouteRules
Allows you to define complex routing logic in the Nitro Server Engine, including caching, redirects, proxies, and more.
2.2 Type signatures
function extendRouteRules(route: string, rule: NitroRouteConfig, options: ExtendRouteRulesOptions): void
parameters
- route: The routing pattern to match.
- rule: Rule configurations applied to matching routes.
- options: Optional parameter passed to the configuration, whether to override an existing configuration.
2.3 NitroRouteConfig
connector
interface NitroRouteConfig {
cache?: CacheOptions | false; // Cache Settings
headers?: Record<string, string>; // HTTP beginning or end
redirect?: string | { to: string; statusCode?: HTTPStatusCode }; // redirects
prerender?: boolean; // Pre-rendering Settings
proxy?: string | ({ to: string } & ProxyOptions); // Proxy Settings
isr?: number | boolean; // Incremental static regeneration settings
cors?: boolean; // CORS be in favor of
swr?: boolean | number; // Revalidation request
static?: boolean | number; // Static request settings
}
2.4 Examples
Below is a complete example of setting up redirection and caching:
//
import { createResolver, defineNuxtModule, extendRouteRules, extendPages } from '@nuxt/kit';
export default defineNuxtModule({
setup(options) {
const resolver = createResolver();
extendPages((pages) => {
({
name: 'new-preview',
path: '/new-preview',
file: ('runtime/'),
});
});
extendRouteRules('/preview', {
redirect: {
to: '/new-preview',
statusCode: 302, // 301 for permanent redirection,302 For temporary redirection
},
});
extendRouteRules('/new-preview', {
cache: {
maxAge: 60 * 60 * 24, // Set cache time to one day
},
});
}
});
2.5 Practical application scenarios
- SEO Optimization: Redirecting old routes to new routes improves user experience and SEO performance.
- cache control: Improve application performance by setting different caching policies based on content changes.
3. addRouteMiddleware
: Registered Routing Middleware
3.1 Functional description
addRouteMiddleware
Allows you to register one or more middleware to handle routing requests such as authentication, permission checking, etc.
3.2 Type signatures
function addRouteMiddleware(input: NuxtMiddleware | NuxtMiddleware[], options: AddRouteMiddlewareOptions): void
parameters
- input: A middleware object or array of middleware objects that must contain a name and path.
- options: Optional parameter that controls whether to override existing middleware.
3.3 NuxtMiddleware
typology
type NuxtMiddleware = {
name: string; // Middleware name
path: string; // Middleware path
global?: boolean; // If the middleware is global.
}
3.4 Example code
The following is an example of authentication middleware:
// runtime/
export default defineNuxtRouteMiddleware((to, from) => {
if ( !== '/login' && !isAuthenticated()) {
return navigateTo('/login'); // If the user is not authenticated,then navigate to the login page
}
});
3.5 Practical application scenarios
- access control: Check if the user is logged in and control access to certain sensitive pages.
- Log tracking:: Record request logs for subsequent analysis and debugging.
4. Example of code structure
Below is an example of the code structure of a simple Nuxt module, incorporating the previous concepts:
//
import { createResolver, defineNuxtModule, extendPages, extendRouteRules, addRouteMiddleware } from '@nuxt/kit';
export default defineNuxtModule({
setup(options) {
const resolver = createResolver();
// Expanded Page Routing
extendPages((pages) => {
({
name: 'example',
path: '/example',
file: ('runtime/'),
});
});
// Expanding Routing Rules
extendRouteRules('/home', {
redirect: {
to: '/example',
statusCode: 301,
},
});
// Add Middleware
addRouteMiddleware(
{ name: 'auth', path: '/auth', global: true },
{ override: true }
);
}
});
With this example, you can see how multiple functions can be combined in a single module to implement complex routing logic and functionality.
summarize
The Nuxt Kit provides extremely powerful page and route management functionality to meet a wide range of development needs. This is accomplished through theextendPages
、extendRouteRules
cap (a poem)addRouteMiddleware
, developers are free to modify and extend the routing logic of the application. When building large applications, these tools can greatly improve development efficiency and application maintainability.
For the rest of the article, please click to jump to the personal blog page or scan the code to follow or WeChat search:Programming Intelligence Front-End to Full-Stack Communication and Growth
, read the full article:Page and Route Management in the Nuxt Kit | cmdragon's Blog
Past articles are archived:
- Contextualization in the Nuxt Kit | cmdragon's Blog
- Nuxt Kit Component Management: Registration and Auto Import | cmdragon's Blog
- Nuxt Kit Auto Import: Manage Your Modules and Combinatorial Functions Efficiently | cmdragon's Blog
- Checking module compatibility with Nuxt versions using the Nuxt Kit | cmdragon's Blog
- A Guide to Using the Nuxt Kit: From Load to Build | cmdragon's Blog
- Nuxt Kit User's Guide: Module Creation and Management | cmdragon's Blog
- Upgrading an existing nuxt project version with nuxi upgrade | cmdragon's Blog
- How to use TypeScript effectively in Nuxt 3 | cmdragon's Blog
- Previewing the Nuxt application with the nuxi preview command | cmdragon's Blog
- Preparing a Nuxt project with the nuxi prepare command | cmdragon's Blog
- Creating a new Nuxt project with nuxi init | cmdragon's Blog
- Use nuxi info to view Nuxt project details | cmdragon's Blog
- Pre-rendering and deployment with nuxi generate | cmdragon's Blog
- Explore Nuxt Devtools: A Comprehensive Guide to Features | cmdragon's Blog
- Detailed guide to launching Nuxt applications with nuxi dev | cmdragon's Blog
- Clean up the Nuxt project with the nuxi clean command | cmdragon's Blog
- Building Nuxt modules with the nuxi build-module command | cmdragon's Blog
- Build your Nuxt application with the nuxi build command | cmdragon's Blog
- Analyzing production packages for Nuxt applications with the nuxi analyze command | cmdragon's Blog
- Quickly create Nuxt application components with nuxi add | cmdragon's Blog
- Updating Nuxt Application Configuration with updateAppConfig | cmdragon's Blog
- Using Nuxt's showError to display a full-screen error page | cmdragon's Blog