From 870e8cacb581b0211e1f6389819e1925aee76e7a Mon Sep 17 00:00:00 2001 From: Sivaprasath <121082414+sivaprasath2004@users.noreply.github.com> Date: Sat, 20 Jul 2024 21:50:30 +0530 Subject: [PATCH 1/5] Delete courses/Next.Js directory --- .../Authentication/Implement-Auth.md | 77 ------ .../Intermediate-level/Authentication/JWT.md | 53 ---- .../Authentication/Role-based.md | 61 ----- .../Authentication/_category_.json | 8 - .../Authentication/protection-Routes.md | 73 ------ .../Data-Fetching/GraphQl.md | 69 ------ .../Data-Fetching/Handling.md | 66 ----- .../Intermediate-level/Data-Fetching/SWR.md | 48 ---- .../Data-Fetching/_category_.json | 8 - .../Data-Fetching/fetching-Data.md | 105 -------- .../Internationalization/Handling-dynamic.md | 60 ----- .../Internationalization/Introduction.md | 72 ------ .../Loading-and-Managing.md | 79 ------ .../Internationalization/_category_.json | 8 - .../Middleware/Introduction.md | 86 ------- .../Middleware/Middleware-concept.md | 55 ----- .../Middleware/_category_.json | 8 - .../Middleware/routing-tech.md | 42 ---- .../Intermediate-level/_category_.json | 8 - courses/Next.Js/Overview.md | 80 ------- courses/Next.Js/_category_.json | 8 - .../Advance-Routing/Customizing.md | 98 -------- .../Advance-Routing/Dynamic-Route.md | 80 ------- .../Advance-Routing/_category_.json | 8 - .../Advance-data-fetching/_category_.json | 8 - .../dynamic-generation.md | 122 ---------- .../static-generation.md | 76 ------ .../Advance-server-side-render/SSR.md | 160 ------------- .../_category_.json | 8 - .../Advance-server-side-render/customize.md | 142 ----------- .../advance-level/GraphQL/Introduction.md | 106 -------- .../advance-level/GraphQL/_category_.json | 8 - .../advance-level/GraphQL/apollo-client.md | 226 ------------------ courses/Next.Js/advance-level/_category_.json | 8 - .../beginner-level/Introduction/Frameworks.md | 65 ----- .../Introduction/_category_.json | 8 - .../Introduction/introduction.md | 67 ------ .../beginner-level/Introduction/settingUp.md | 65 ----- .../Pages-and-routing/FIlebase-Routing.md | 80 ------- .../Pages-and-routing/_category_.json | 8 - .../Pages-and-routing/creating-pages.md | 33 --- .../Next.Js/beginner-level/Routes/Database.md | 120 ---------- .../beginner-level/Routes/Introduction.md | 48 ---- .../beginner-level/Routes/_category_.json | 8 - .../Started/Running-development.md | 64 ----- .../beginner-level/Started/_category_.json | 8 - .../Started/creating-project.md | 67 ------ .../beginner-level/Styling/Libraries.md | 80 ------- .../beginner-level/Styling/_category_.json | 8 - .../beginner-level/Styling/css-styling.md | 104 -------- .../Next.Js/beginner-level/_category_.json | 8 - .../static-and-serverSide/_category_.json | 8 - .../static-and-serverSide/concept.md | 160 ------------- .../static-and-serverSide/introduction.md | 123 ---------- 54 files changed, 3256 deletions(-) delete mode 100644 courses/Next.Js/Intermediate-level/Authentication/Implement-Auth.md delete mode 100644 courses/Next.Js/Intermediate-level/Authentication/JWT.md delete mode 100644 courses/Next.Js/Intermediate-level/Authentication/Role-based.md delete mode 100644 courses/Next.Js/Intermediate-level/Authentication/_category_.json delete mode 100644 courses/Next.Js/Intermediate-level/Authentication/protection-Routes.md delete mode 100644 courses/Next.Js/Intermediate-level/Data-Fetching/GraphQl.md delete mode 100644 courses/Next.Js/Intermediate-level/Data-Fetching/Handling.md delete mode 100644 courses/Next.Js/Intermediate-level/Data-Fetching/SWR.md delete mode 100644 courses/Next.Js/Intermediate-level/Data-Fetching/_category_.json delete mode 100644 courses/Next.Js/Intermediate-level/Data-Fetching/fetching-Data.md delete mode 100644 courses/Next.Js/Intermediate-level/Internationalization/Handling-dynamic.md delete mode 100644 courses/Next.Js/Intermediate-level/Internationalization/Introduction.md delete mode 100644 courses/Next.Js/Intermediate-level/Internationalization/Loading-and-Managing.md delete mode 100644 courses/Next.Js/Intermediate-level/Internationalization/_category_.json delete mode 100644 courses/Next.Js/Intermediate-level/Middleware/Introduction.md delete mode 100644 courses/Next.Js/Intermediate-level/Middleware/Middleware-concept.md delete mode 100644 courses/Next.Js/Intermediate-level/Middleware/_category_.json delete mode 100644 courses/Next.Js/Intermediate-level/Middleware/routing-tech.md delete mode 100644 courses/Next.Js/Intermediate-level/_category_.json delete mode 100644 courses/Next.Js/Overview.md delete mode 100644 courses/Next.Js/_category_.json delete mode 100644 courses/Next.Js/advance-level/Advance-Routing/Customizing.md delete mode 100644 courses/Next.Js/advance-level/Advance-Routing/Dynamic-Route.md delete mode 100644 courses/Next.Js/advance-level/Advance-Routing/_category_.json delete mode 100644 courses/Next.Js/advance-level/Advance-data-fetching/_category_.json delete mode 100644 courses/Next.Js/advance-level/Advance-data-fetching/dynamic-generation.md delete mode 100644 courses/Next.Js/advance-level/Advance-data-fetching/static-generation.md delete mode 100644 courses/Next.Js/advance-level/Advance-server-side-render/SSR.md delete mode 100644 courses/Next.Js/advance-level/Advance-server-side-render/_category_.json delete mode 100644 courses/Next.Js/advance-level/Advance-server-side-render/customize.md delete mode 100644 courses/Next.Js/advance-level/GraphQL/Introduction.md delete mode 100644 courses/Next.Js/advance-level/GraphQL/_category_.json delete mode 100644 courses/Next.Js/advance-level/GraphQL/apollo-client.md delete mode 100644 courses/Next.Js/advance-level/_category_.json delete mode 100644 courses/Next.Js/beginner-level/Introduction/Frameworks.md delete mode 100644 courses/Next.Js/beginner-level/Introduction/_category_.json delete mode 100644 courses/Next.Js/beginner-level/Introduction/introduction.md delete mode 100644 courses/Next.Js/beginner-level/Introduction/settingUp.md delete mode 100644 courses/Next.Js/beginner-level/Pages-and-routing/FIlebase-Routing.md delete mode 100644 courses/Next.Js/beginner-level/Pages-and-routing/_category_.json delete mode 100644 courses/Next.Js/beginner-level/Pages-and-routing/creating-pages.md delete mode 100644 courses/Next.Js/beginner-level/Routes/Database.md delete mode 100644 courses/Next.Js/beginner-level/Routes/Introduction.md delete mode 100644 courses/Next.Js/beginner-level/Routes/_category_.json delete mode 100644 courses/Next.Js/beginner-level/Started/Running-development.md delete mode 100644 courses/Next.Js/beginner-level/Started/_category_.json delete mode 100644 courses/Next.Js/beginner-level/Started/creating-project.md delete mode 100644 courses/Next.Js/beginner-level/Styling/Libraries.md delete mode 100644 courses/Next.Js/beginner-level/Styling/_category_.json delete mode 100644 courses/Next.Js/beginner-level/Styling/css-styling.md delete mode 100644 courses/Next.Js/beginner-level/_category_.json delete mode 100644 courses/Next.Js/beginner-level/static-and-serverSide/_category_.json delete mode 100644 courses/Next.Js/beginner-level/static-and-serverSide/concept.md delete mode 100644 courses/Next.Js/beginner-level/static-and-serverSide/introduction.md diff --git a/courses/Next.Js/Intermediate-level/Authentication/Implement-Auth.md b/courses/Next.Js/Intermediate-level/Authentication/Implement-Auth.md deleted file mode 100644 index 53658058b..000000000 --- a/courses/Next.Js/Intermediate-level/Authentication/Implement-Auth.md +++ /dev/null @@ -1,77 +0,0 @@ ---- -id: lesson-1 -title: "Authentication and Authorization in Next.js" -sidebar_label: Authentication and Authorization -sidebar_position: 1 -description: "Authentication and Authorization in Next.js" -tags: [courses,intermediate-level,FramWorks,Introduction] ---- - - -Implementing authentication and authorization in Next.js can be streamlined using libraries like NextAuth.js for handling various authentication strategies, JWT-based authentication for token management, and role-based access control to protect routes and API endpoints. - -#### Implementing Authentication with NextAuth.js - -NextAuth.js is a flexible authentication library for Next.js applications. It supports various authentication providers like Google, GitHub, and custom email/password. - -1. **Install NextAuth.js**: - ```bash - npm install next-auth - ``` - -2. **Configure NextAuth.js**: - - Create a new API route for NextAuth in `src/pages/api/auth/[...nextauth].js`: - ```javascript - // src/pages/api/auth/[...nextauth].js - import NextAuth from 'next-auth'; - import Providers from 'next-auth/providers'; - - export default NextAuth({ - providers: [ - Providers.Google({ - clientId: process.env.GOOGLE_CLIENT_ID, - clientSecret: process.env.GOOGLE_CLIENT_SECRET, - }), - // Add other providers here - ], - database: process.env.DATABASE_URL, // Optional: For storing user accounts in a database - }); - ``` - -3. **Add Environment Variables**: - - Create a `.env.local` file in the root of your project and add the required environment variables: - ```env - GOOGLE_CLIENT_ID=your-google-client-id - GOOGLE_CLIENT_SECRET=your-google-client-secret - DATABASE_URL=your-database-url - ``` - -4. **Add Authentication to Pages**: - - Use the `useSession` hook to access the authentication session: - ```javascript - // src/pages/index.js - import { useSession, signIn, signOut } from 'next-auth/client'; - - export default function Home() { - const [session, loading] = useSession(); - - return ( -
-

NextAuth.js Authentication

- {loading &&

Loading...

} - {!session && ( -
-

You are not signed in.

- -
- )} - {session && ( -
-

Signed in as {session.user.email}

- -
- )} -
- ); - } - ``` \ No newline at end of file diff --git a/courses/Next.Js/Intermediate-level/Authentication/JWT.md b/courses/Next.Js/Intermediate-level/Authentication/JWT.md deleted file mode 100644 index cd2d48999..000000000 --- a/courses/Next.Js/Intermediate-level/Authentication/JWT.md +++ /dev/null @@ -1,53 +0,0 @@ ---- -id: lesson-2 -title: "JWT-Based Authentication" -sidebar_label: JWT-Based Authentication -sidebar_position: 2 -description: "JWT-Based Authentication" -tags: [courses,intermediate-level,FramWorks,Introduction] ---- - - -JWT (JSON Web Token) is a common method for securing APIs by encoding user information within a token. - -1. **Install JWT Dependencies**: - ```bash - npm install jsonwebtoken - ``` - -2. **Generate JWTs**: - ```javascript - // src/utils/jwt.js - import jwt from 'jsonwebtoken'; - - const secret = process.env.JWT_SECRET; - - export function generateToken(user) { - return jwt.sign({ id: user.id, email: user.email }, secret, { expiresIn: '1h' }); - } - - export function verifyToken(token) { - try { - return jwt.verify(token, secret); - } catch (err) { - return null; - } - } - ``` - -3. **Protecting API Routes**: - ```javascript - // src/pages/api/protected.js - import { verifyToken } from '../../utils/jwt'; - - export default function handler(req, res) { - const token = req.headers.authorization?.split(' ')[1]; - const user = verifyToken(token); - - if (!user) { - return res.status(401).json({ message: 'Unauthorized' }); - } - - res.status(200).json({ message: 'This is a protected route', user }); - } - ``` \ No newline at end of file diff --git a/courses/Next.Js/Intermediate-level/Authentication/Role-based.md b/courses/Next.Js/Intermediate-level/Authentication/Role-based.md deleted file mode 100644 index 69a4ad9a9..000000000 --- a/courses/Next.Js/Intermediate-level/Authentication/Role-based.md +++ /dev/null @@ -1,61 +0,0 @@ ---- -id: lesson-3 -title: "Role-Based Access Control" -sidebar_label: Protecting Routes and API Endpoints -sidebar_position: 3 -description: "Role-Based Access Control" -tags: [courses,intermediate-level,FramWorks,Introduction] ---- - - - -1. **Assign Roles to Users**: - - Modify your user model to include roles: - ```javascript - // src/models/User.js - import mongoose from 'mongoose'; - - const UserSchema = new mongoose.Schema({ - name: String, - email: String, - role: { - type: String, - enum: ['user', 'admin'], - default: 'user', - }, - }); - - export default mongoose.models.User || mongoose.model('User', UserSchema); - ``` - -2. **Create Middleware for Role-Based Access Control**: - ```javascript - // src/utils/withRole.js - import { verifyToken } from './jwt'; - - export function withRole(handler, role) { - return async (req, res) => { - const token = req.headers.authorization?.split(' ')[1]; - const user = verifyToken(token); - - if (!user || user.role !== role) { - return res.status(403).json({ message: 'Forbidden' }); - } - - req.user = user; - return handler(req, res); - }; - } - ``` - -3. **Protect Routes with Role-Based Access Control**: - ```javascript - // src/pages/api/admin.js - import { withRole } from '../../utils/withRole'; - - const handler = (req, res) => { - res.status(200).json({ message: 'Admin route', user: req.user }); - }; - - export default withRole(handler, 'admin'); - ``` diff --git a/courses/Next.Js/Intermediate-level/Authentication/_category_.json b/courses/Next.Js/Intermediate-level/Authentication/_category_.json deleted file mode 100644 index 005cbdc85..000000000 --- a/courses/Next.Js/Intermediate-level/Authentication/_category_.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "label": "Authentication and Authorization", - "position": 2, - "link": { - "type": "generated-index", - "description": "Learn Next.Js Authentication and Authorization." - } - } \ No newline at end of file diff --git a/courses/Next.Js/Intermediate-level/Authentication/protection-Routes.md b/courses/Next.Js/Intermediate-level/Authentication/protection-Routes.md deleted file mode 100644 index ce7bd3cdb..000000000 --- a/courses/Next.Js/Intermediate-level/Authentication/protection-Routes.md +++ /dev/null @@ -1,73 +0,0 @@ ---- -id: lesson-4 -title: "Protecting Routes and API Endpoints" -sidebar_label: Protecting Routes and API Endpoints -sidebar_position: 4 -description: "Protecting Routes and API Endpoints" -tags: [courses,intermediate-level,FramWorks,Introduction] ---- - - -1. **Protecting Next.js Pages**: - - Use the `getServerSideProps` function to protect pages: - ```javascript - // src/pages/protected.js - import { getSession } from 'next-auth/client'; - - export default function ProtectedPage({ session }) { - if (!session) { - return

Access Denied

; - } - - return

Welcome, {session.user.email}

; - } - - export async function getServerSideProps(context) { - const session = await getSession(context); - - if (!session) { - return { - redirect: { - destination: '/api/auth/signin', - permanent: false, - }, - }; - } - - return { - props: { session }, - }; - } - ``` - -2. **Protecting API Endpoints with Middleware**: - ```javascript - // src/utils/withAuth.js - import { verifyToken } from './jwt'; - - export function withAuth(handler) { - return async (req, res) => { - const token = req.headers.authorization?.split(' ')[1]; - const user = verifyToken(token); - - if (!user) { - return res.status(401).json({ message: 'Unauthorized' }); - } - - req.user = user; - return handler(req, res); - }; - } - ``` - - ```javascript - // src/pages/api/protected.js - import { withAuth } from '../../utils/withAuth'; - - const handler = (req, res) => { - res.status(200).json({ message: 'Protected route', user: req.user }); - }; - - export default withAuth(handler); - ``` - \ No newline at end of file diff --git a/courses/Next.Js/Intermediate-level/Data-Fetching/GraphQl.md b/courses/Next.Js/Intermediate-level/Data-Fetching/GraphQl.md deleted file mode 100644 index d32a1a349..000000000 --- a/courses/Next.Js/Intermediate-level/Data-Fetching/GraphQl.md +++ /dev/null @@ -1,69 +0,0 @@ ---- -id: lesson-3 -title: "Using GraphQL with Next.js" -sidebar_label: Data Fetching and Caching -sidebar_position: 3 -description: "Using GraphQL with Next.js" -tags: [courses,intermediate-level,FramWorks,Introduction] ---- - - -You can use GraphQL with Next.js using Apollo Client or other GraphQL clients. - -1. **Install Apollo Client**: - ```bash - npm install @apollo/client graphql - ``` - -2. **Setup Apollo Client**: - ```javascript - // src/lib/apolloClient.js - import { ApolloClient, InMemoryCache } from '@apollo/client'; - - const client = new ApolloClient({ - uri: 'https://your-graphql-endpoint', - cache: new InMemoryCache(), - }); - - export default client; - ``` - -3. **Use Apollo Client in a Page**: - ```javascript - // src/pages/index.js - import { ApolloProvider, gql, useQuery } from '@apollo/client'; - import client from '../lib/apolloClient'; - - const GET_POSTS = gql` - query GetPosts { - posts { - id - title - } - } - `; - - function Posts() { - const { loading, error, data } = useQuery(GET_POSTS); - - if (loading) return

Loading...

; - if (error) return

Error :(

; - - return ( - - ); - } - - export default function Home() { - return ( - -

Posts

- -
- ); - } - ``` diff --git a/courses/Next.Js/Intermediate-level/Data-Fetching/Handling.md b/courses/Next.Js/Intermediate-level/Data-Fetching/Handling.md deleted file mode 100644 index cc839c93b..000000000 --- a/courses/Next.Js/Intermediate-level/Data-Fetching/Handling.md +++ /dev/null @@ -1,66 +0,0 @@ ---- -id: lesson-4 -title: "Handling Data Fetching Errors" -sidebar_label: Handling Fetching Errors -sidebar_position: 4 -description: "Handling Data Fetching Errors" -tags: [courses,intermediate-level,FramWorks,Introduction] ---- - - -Handling errors in data fetching is crucial to provide a good user experience. - -1. **Error Handling with `getStaticProps` and `getServerSideProps`**: - ```javascript - export async function getStaticProps() { - try { - const res = await fetch('https://jsonplaceholder.typicode.com/posts'); - const posts = await res.json(); - return { props: { posts } }; - } catch (error) { - return { props: { error: 'Failed to fetch data' } }; - } - } - - export default function Home({ posts, error }) { - if (error) { - return
{error}
; - } - - return ( -
-

Posts

- -
- ); - } - ``` - -2. **Error Handling with SWR**: - ```javascript - import useSWR from 'swr'; - - const fetcher = url => fetch(url).then(res => res.json()); - - export default function Home() { - const { data: posts, error } = useSWR('https://jsonplaceholder.typicode.com/posts', fetcher); - - if (error) return
Failed to load: {error.message}
; - if (!posts) return
Loading...
; - - return ( -
-

Posts

- -
- ); - } - ``` \ No newline at end of file diff --git a/courses/Next.Js/Intermediate-level/Data-Fetching/SWR.md b/courses/Next.Js/Intermediate-level/Data-Fetching/SWR.md deleted file mode 100644 index e1daeacb4..000000000 --- a/courses/Next.Js/Intermediate-level/Data-Fetching/SWR.md +++ /dev/null @@ -1,48 +0,0 @@ ---- -id: lesson-2 -title: "SWR (Stale-While-Revalidate) for Data Fetching and Caching" -sidebar_label: SWR (Stale-While-Revalidate) -sidebar_position: 2 -description: "SWR (Stale-While-Revalidate) for Data Fetching and Caching" -tags: [courses,intermediate-level,FramWorks,Introduction] ---- - - - -SWR is a React Hooks library for data fetching, providing features like caching, revalidation, focus tracking, and more. - -1. **Install SWR**: - ```bash - npm install swr - ``` - -2. **Using SWR**: - ```javascript - // src/pages/index.js - import useSWR from 'swr'; - - const fetcher = url => fetch(url).then(res => res.json()); - - export default function Home() { - const { data: posts, error } = useSWR('https://jsonplaceholder.typicode.com/posts', fetcher); - - if (error) return
Failed to load
; - if (!posts) return
Loading...
; - - return ( -
-

Posts

- -
- ); - } - ``` - -**Key Features of SWR**: -- **Stale-While-Revalidate**: Data is returned from the cache first (stale), then fetches the latest data in the background (revalidate). -- **Automatic Revalidation**: Data is revalidated on focus, network reconnect, and interval-based revalidation. -- **Error Handling**: Provides built-in error handling and state management. diff --git a/courses/Next.Js/Intermediate-level/Data-Fetching/_category_.json b/courses/Next.Js/Intermediate-level/Data-Fetching/_category_.json deleted file mode 100644 index 23e48253e..000000000 --- a/courses/Next.Js/Intermediate-level/Data-Fetching/_category_.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "label": "Data Fetching", - "position": 1, - "link": { - "type": "generated-index", - "description": "Learn Next.Js Data Fetching." - } - } \ No newline at end of file diff --git a/courses/Next.Js/Intermediate-level/Data-Fetching/fetching-Data.md b/courses/Next.Js/Intermediate-level/Data-Fetching/fetching-Data.md deleted file mode 100644 index 82936046a..000000000 --- a/courses/Next.Js/Intermediate-level/Data-Fetching/fetching-Data.md +++ /dev/null @@ -1,105 +0,0 @@ ---- -id: lesson-1 -title: "Data Fetching and Caching in Next.js" -sidebar_label: Data Fetching and Caching -sidebar_position: 1 -description: "Data Fetching and Caching in Next.js" -tags: [courses,intermediate-level,FramWorks,Introduction] ---- - - -Efficient data fetching and caching are crucial for building performant and responsive web applications. Next.js provides several methods for fetching data, including the use of the SWR (Stale-While-Revalidate) library for caching. Additionally, Next.js supports fetching data from GraphQL APIs. - -#### Fetching Data from APIs - -Next.js allows you to fetch data in different ways depending on your requirements. The primary methods are: - -1. **`getStaticProps`**: Fetch data at build time for static generation. -2. **`getServerSideProps`**: Fetch data on each request for server-side rendering. -3. **Client-Side Fetching**: Fetch data on the client side, typically using `useEffect`. - -**Example with `getStaticProps`**: -```javascript -// src/pages/index.js -export async function getStaticProps() { - const res = await fetch('https://jsonplaceholder.typicode.com/posts'); - const posts = await res.json(); - - return { - props: { - posts, - }, - }; -} - -export default function Home({ posts }) { - return ( -
-

Posts

- -
- ); -} -``` - -**Example with `getServerSideProps`**: -```javascript -// src/pages/index.js -export async function getServerSideProps() { - const res = await fetch('https://jsonplaceholder.typicode.com/posts'); - const posts = await res.json(); - - return { - props: { - posts, - }, - }; -} - -export default function Home({ posts }) { - return ( -
-

Posts

- -
- ); -} -``` - -**Example with Client-Side Fetching**: -```javascript -// src/pages/index.js -import { useState, useEffect } from 'react'; - -export default function Home() { - const [posts, setPosts] = useState([]); - - useEffect(() => { - async function fetchData() { - const res = await fetch('https://jsonplaceholder.typicode.com/posts'); - const posts = await res.json(); - setPosts(posts); - } - fetchData(); - }, []); - - return ( -
-

Posts

- -
- ); -} -``` \ No newline at end of file diff --git a/courses/Next.Js/Intermediate-level/Internationalization/Handling-dynamic.md b/courses/Next.Js/Intermediate-level/Internationalization/Handling-dynamic.md deleted file mode 100644 index 68a0c6ab8..000000000 --- a/courses/Next.Js/Intermediate-level/Internationalization/Handling-dynamic.md +++ /dev/null @@ -1,60 +0,0 @@ ---- -id: lesson-3 -title: "Handling Dynamic Content in Different Languages" -sidebar_label: Handling Languages -sidebar_position: 3 -description: "Handling Dynamic Content in Different Languages" -tags: [courses,intermediate-level,FramWorks,Introduction] ---- - - -1. **Dynamic Routes with i18n**: - - Create dynamic route files and fetch localized content based on the locale: - ```javascript - // pages/[locale]/[slug].js - import { useRouter } from 'next/router'; - import { useTranslation } from 'next-i18next'; - - export default function Post({ post }) { - const { t } = useTranslation('common'); - - return ( -
-

{t(post.title)}

-

{t(post.content)}

-
- ); - } - - export async function getStaticPaths() { - // Fetch or define paths for all locales - const paths = [ - { params: { locale: 'en', slug: 'hello-world' } }, - { params: { locale: 'fr', slug: 'bonjour-le-monde' } }, - { params: { locale: 'de', slug: 'hallo-welt' } }, - ]; - return { paths, fallback: false }; - } - - export async function getStaticProps({ params }) { - const { locale, slug } = params; - const post = await fetchPostData(locale, slug); - - return { - props: { - post, - ...(await serverSideTranslations(locale, ['common'])), - }, - }; - } - ``` - -2. **Fetching Localized Data**: - - Implement a function to fetch localized data: - ```javascript - async function fetchPostData(locale, slug) { - const res = await fetch(`https://api.example.com/posts?locale=${locale}&slug=${slug}`); - const data = await res.json(); - return data; - } - ``` \ No newline at end of file diff --git a/courses/Next.Js/Intermediate-level/Internationalization/Introduction.md b/courses/Next.Js/Intermediate-level/Internationalization/Introduction.md deleted file mode 100644 index 552e7fdab..000000000 --- a/courses/Next.Js/Intermediate-level/Internationalization/Introduction.md +++ /dev/null @@ -1,72 +0,0 @@ ---- -id: lesson-1 -title: "Internationalization (i18n) in Next.js" -sidebar_label: Internationalization (i18n) -sidebar_position: 1 -description: "Internationalization (i18n) in Next.js" -tags: [courses,intermediate-level,FramWorks,Introduction] ---- - - -Internationalization (i18n) is crucial for creating applications that support multiple languages and locales. Next.js offers built-in support for internationalized routing and provides tools to load and manage translations effectively. - -#### Setting Up Internationalization in Next.js - -1. **Install Required Packages**: - - If you need a library to help with translations, such as `next-i18next`, install it: - ```bash - npm install next-i18next - ``` - -2. **Configure `next.config.js` for i18n**: - - Add i18n configuration to your `next.config.js` file: - ```javascript - // next.config.js - module.exports = { - i18n: { - locales: ['en', 'fr', 'de'], // List of supported locales - defaultLocale: 'en', // Default locale - }, - }; - ``` - -#### Using the Next.js i18n Routing Feature - -1. **Creating Locale-specific Files**: - - Create directories and files for each locale under the `pages` directory: - ``` - pages/ - ├── index.js - ├── about.js - ├── fr/ - │ ├── index.js - │ └── about.js - ├── de/ - │ ├── index.js - │ └── about.js - ``` - -2. **Linking Between Locales**: - - Use the `next/link` component to link between different locales: - ```javascript - // pages/index.js - import Link from 'next/link'; - import { useRouter } from 'next/router'; - - export default function Home() { - const { locale, locales, asPath } = useRouter(); - - return ( -
-

Hello World

- -
- ); - } - ``` diff --git a/courses/Next.Js/Intermediate-level/Internationalization/Loading-and-Managing.md b/courses/Next.Js/Intermediate-level/Internationalization/Loading-and-Managing.md deleted file mode 100644 index b86bcc742..000000000 --- a/courses/Next.Js/Intermediate-level/Internationalization/Loading-and-Managing.md +++ /dev/null @@ -1,79 +0,0 @@ ---- -id: lesson-2 -title: "Loading and Managing Translations" -sidebar_label: Loading and Managing -sidebar_position: 2 -description: "Loading and Managing Translations" -tags: [courses,intermediate-level,FramWorks,Introduction] ---- - - -1. **Using `next-i18next`**: - - Initialize `next-i18next` in your project: - ```javascript - // i18n.js - const NextI18Next = require('next-i18next').default; - - const NextI18NextInstance = new NextI18Next({ - defaultLanguage: 'en', - otherLanguages: ['fr', 'de'], - }); - - module.exports = NextI18NextInstance; - module.exports.default = NextI18NextInstance; - ``` - -2. **Adding Translation Files**: - - Create translation files for each language under a `public/locales` directory: - ``` - public/ - └── locales/ - ├── en/ - │ └── common.json - ├── fr/ - │ └── common.json - └── de/ - └── common.json - ``` - - Example content for `common.json`: - ```json - // public/locales/en/common.json - { - "welcome": "Welcome", - "about": "About Us" - } - - // public/locales/fr/common.json - { - "welcome": "Bienvenue", - "about": "À propos de nous" - } - - // public/locales/de/common.json - { - "welcome": "Willkommen", - "about": "Über uns" - } - ``` - -3. **Using Translations in Components**: - - Use the `useTranslation` hook provided by `next-i18next` to load and use translations: - ```javascript - // pages/index.js - import { useTranslation } from 'next-i18next'; - import { serverSideTranslations } from 'next-i18next/serverSideTranslations'; - - export default function Home() { - const { t } = useTranslation('common'); - - return

{t('welcome')}

; - } - - export async function getStaticProps({ locale }) { - return { - props: { - ...(await serverSideTranslations(locale, ['common'])), - }, - }; - } - ``` \ No newline at end of file diff --git a/courses/Next.Js/Intermediate-level/Internationalization/_category_.json b/courses/Next.Js/Intermediate-level/Internationalization/_category_.json deleted file mode 100644 index ce6e40b86..000000000 --- a/courses/Next.Js/Intermediate-level/Internationalization/_category_.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "label": "Internationalization (i18n)", - "position": 4, - "link": { - "type": "generated-index", - "description": "Learn Next.Js Internationalization (i18n)." - } - } \ No newline at end of file diff --git a/courses/Next.Js/Intermediate-level/Middleware/Introduction.md b/courses/Next.Js/Intermediate-level/Middleware/Introduction.md deleted file mode 100644 index 29449db6a..000000000 --- a/courses/Next.Js/Intermediate-level/Middleware/Introduction.md +++ /dev/null @@ -1,86 +0,0 @@ ---- -id: lesson-1 -title: "Middleware and Custom Server in Next.js" -sidebar_label: Middleware and Custom Server in Next.js -sidebar_position: 1 -description: "Middleware and Custom Server in Next.js" -tags: [courses,intermediate-level,FramWorks,Introduction] ---- - - -Middleware and custom servers in Next.js can enhance functionality by adding features like logging, authentication, and advanced routing. Below, we'll explore how to implement middleware, set up a custom server using Express.js, and utilize middleware for various purposes. - -#### Understanding and Using Middleware in Next.js - -Middleware in Next.js can be added at the API route level or through a custom server setup. - -1. **API Route Middleware**: - - Middleware functions can be added directly in API routes to handle specific tasks like logging and authentication. - - **Example: Logging Middleware for an API Route**: - ```javascript - // src/pages/api/logged.js - export default function handler(req, res) { - console.log(`Request method: ${req.method}`); - res.status(200).json({ message: 'Logged request method' }); - } - ``` - -2. **Global Middleware Using Custom Server**: - - For more complex middleware usage, setting up a custom server with Express.js allows applying middleware globally. - -#### Creating a Custom Server with Express.js - -A custom server can provide more control over the request handling process. Here's how to set up a custom server with Express.js: - -1. **Install Required Packages**: - ```bash - npm install express - ``` - -2. **Set Up the Custom Server**: - - Create a `server.js` file at the root of your project: - ```javascript - // server.js - const express = require('express'); - const next = require('next'); - - const dev = process.env.NODE_ENV !== 'production'; - const app = next({ dev }); - const handle = app.getRequestHandler(); - - app.prepare().then(() => { - const server = express(); - - // Example of a custom middleware for logging - server.use((req, res, next) => { - console.log(`Request URL: ${req.url}`); - next(); - }); - - // Example route - server.get('/custom', (req, res) => { - return app.render(req, res, '/custom', req.query); - }); - - // Default Next.js request handler - server.all('*', (req, res) => { - return handle(req, res); - }); - - server.listen(3000, err => { - if (err) throw err; - console.log('> Ready on http://localhost:3000'); - }); - }); - ``` - -3. **Modify `package.json` to Use the Custom Server**: - ```json - // package.json - "scripts": { - "dev": "node server.js", - "build": "next build", - "start": "NODE_ENV=production node server.js" - } - ``` diff --git a/courses/Next.Js/Intermediate-level/Middleware/Middleware-concept.md b/courses/Next.Js/Intermediate-level/Middleware/Middleware-concept.md deleted file mode 100644 index 811cef2a9..000000000 --- a/courses/Next.Js/Intermediate-level/Middleware/Middleware-concept.md +++ /dev/null @@ -1,55 +0,0 @@ ---- -id: lesson-2 -title: "Using Middleware for Logging, Authentication, etc." -sidebar_label: Using Middleware for Logging, Authentication, etc. -sidebar_position: 2 -description: "Using Middleware for Logging, Authentication, etc." -tags: [courses,intermediate-level,FramWorks,Introduction] ---- - - -1. **Logging Middleware**: - ```javascript - server.use((req, res, next) => { - console.log(`Request URL: ${req.url}, Method: ${req.method}`); - next(); - }); - ``` - -2. **Authentication Middleware**: - ```javascript - const jwt = require('jsonwebtoken'); - - server.use((req, res, next) => { - const token = req.headers.authorization?.split(' ')[1]; - if (token) { - try { - req.user = jwt.verify(token, process.env.JWT_SECRET); - } catch (err) { - return res.status(401).json({ message: 'Invalid Token' }); - } - } - next(); - }); - ``` - -3. **Combining Middleware**: - - Middleware can be combined for various purposes: - ```javascript - server.use((req, res, next) => { - console.log(`Request URL: ${req.url}`); - next(); - }); - - server.use((req, res, next) => { - const token = req.headers.authorization?.split(' ')[1]; - if (token) { - try { - req.user = jwt.verify(token, process.env.JWT_SECRET); - } catch (err) { - return res.status(401).json({ message: 'Invalid Token' }); - } - } - next(); - }); - ``` diff --git a/courses/Next.Js/Intermediate-level/Middleware/_category_.json b/courses/Next.Js/Intermediate-level/Middleware/_category_.json deleted file mode 100644 index df83bef03..000000000 --- a/courses/Next.Js/Intermediate-level/Middleware/_category_.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "label": "Middleware and Custom Server", - "position": 3, - "link": { - "type": "generated-index", - "description": "Learn Next.Js Middleware and Custom Server." - } - } \ No newline at end of file diff --git a/courses/Next.Js/Intermediate-level/Middleware/routing-tech.md b/courses/Next.Js/Intermediate-level/Middleware/routing-tech.md deleted file mode 100644 index 82d99181e..000000000 --- a/courses/Next.Js/Intermediate-level/Middleware/routing-tech.md +++ /dev/null @@ -1,42 +0,0 @@ ---- -id: lesson-3 -title: "Advanced Routing Techniques with a Custom Server" -sidebar_label: Advanced Routing Technique -sidebar_position: 3 -description: "Advanced Routing Techniques with a Custom Server" -tags: [courses,intermediate-level,FramWorks,Introduction] ---- - -A custom server enables more advanced routing capabilities beyond the file-based routing system provided by Next.js. - -1. **Custom Route Handling**: - ```javascript - server.get('/custom-route', (req, res) => { - return app.render(req, res, '/custom', req.query); - }); - ``` - -2. **Dynamic Routing**: - ```javascript - server.get('/post/:id', (req, res) => { - const actualPage = '/post'; - const queryParams = { id: req.params.id }; - return app.render(req, res, actualPage, queryParams); - }); - ``` - -3. **Middleware Specific to Routes**: - ```javascript - server.use('/protected', (req, res, next) => { - const token = req.headers.authorization?.split(' ')[1]; - if (!token) { - return res.status(401).json({ message: 'Unauthorized' }); - } - next(); - }); - - server.get('/protected', (req, res) => { - return res.status(200).json({ message: 'This is a protected route' }); - }); - ``` - \ No newline at end of file diff --git a/courses/Next.Js/Intermediate-level/_category_.json b/courses/Next.Js/Intermediate-level/_category_.json deleted file mode 100644 index 44d8d0893..000000000 --- a/courses/Next.Js/Intermediate-level/_category_.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "label": "Intermediate Level", - "position": 2, - "link": { - "type": "generated-index", - "description": "Learn Next.Js more Topics & Techniques." - } - } \ No newline at end of file diff --git a/courses/Next.Js/Overview.md b/courses/Next.Js/Overview.md deleted file mode 100644 index 011196eb5..000000000 --- a/courses/Next.Js/Overview.md +++ /dev/null @@ -1,80 +0,0 @@ ---- -title: Welcome to Learning Path -sidebar_label: Course Overview -sidebar_position: 1 -description: Next.js Course Outline. -tags: [courses,Next.Js] -keywoards: [courses,Database,Next.Js] -author: [CodeHarborHub, Ajay Dhangar] ---- - - -### Beginner Level - -**1. Introduction to Next.js** - - What is Next.js? - - Comparing Next.js with other frameworks (e.g., React, Angular) - - Setting up the development environment - -**2. Getting Started with Next.js** - - Creating a new Next.js project - - Running the development server & Deploying - -**3. Pages and Routing** - - Creating pages in Next.js - - Understanding the file-based routing system - -**4. Static and Server-Side Rendering** - - Difference between static and server-side rendering - - Concept of Static and server-side rendering - -**5. Styling in Next.js** - - Using CSS in Next.js - - Integrating with CSS-in-JS libraries (e.g., styled-components, emotion) - -**6. API Routes** - - Creating API routes in Next.js - - Connecting API routes to a database - -### Intermediate Level - -**1. Data Fetching and Caching** - - Fetching data from APIs - - SWR (Stale-While-Revalidate) for data fetching and caching - - Using GraphQL with Next.js - - Handling data fetching errors - -**2. Authentication and Authorization** - - Implementing authentication with NextAuth.js - - JWT-based authentication - - Role-based access control - - Protecting routes and API endpoints - -**3. Middleware and Custom Server** - - Understanding and using middleware in Next.js - - Using middleware for logging, authentication, etc. - - Advanced routing techniques with a custom server - -**4. Internationalization (i18n)** - - Setting up internationalization in Next.js - - Loading and managing translations - - Handling dynamic content in different languages - -### Advanced Level - -**1. Advanced Data Fetching** - - Static generation with revalidation - - Combining static and dynamic data fetching - -**2. Advanced Routing Techniques** - - Dynamic API routes - - Customizing the Next.js router - -**3. Next.js and GraphQL** - - Setting up a GraphQL server with Next.js - - Using Apollo Client with Next.js - -**4. Advanced Server-Side Rendering** - - Customizing the server-side rendering process - - Optimizing SSR for performance - \ No newline at end of file diff --git a/courses/Next.Js/_category_.json b/courses/Next.Js/_category_.json deleted file mode 100644 index 206868ec0..000000000 --- a/courses/Next.Js/_category_.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "label": "Next.Js", - "position": 10, - "link": { - "type": "generated-index", - "description": "Learn MongoDB." - } - } \ No newline at end of file diff --git a/courses/Next.Js/advance-level/Advance-Routing/Customizing.md b/courses/Next.Js/advance-level/Advance-Routing/Customizing.md deleted file mode 100644 index 55dd53981..000000000 --- a/courses/Next.Js/advance-level/Advance-Routing/Customizing.md +++ /dev/null @@ -1,98 +0,0 @@ ---- -id: lesson-2 -title: "Customizing the Next.js Router" -sidebar_label: Customizing the Next.js Router -sidebar_position: 2 -description: "Customizing the Next.js Router" -tags: [courses,Advance-level,FramWorks,Introduction] ---- - - - -Next.js allows you to customize the router to add additional functionalities or handle specific routing needs. - -1. **Using Custom Server with Express.js**: - ```javascript - // server.js - const express = require('express'); - const next = require('next'); - - const dev = process.env.NODE_ENV !== 'production'; - const app = next({ dev }); - const handle = app.getRequestHandler(); - - app.prepare().then(() => { - const server = express(); - - server.get('/custom-route', (req, res) => { - return app.render(req, res, '/custom', req.query); - }); - - server.all('*', (req, res) => { - return handle(req, res); - }); - - server.listen(3000, (err) => { - if (err) throw err; - console.log('> Ready on http://localhost:3000'); - }); - }); - ``` - -2. **Adding Custom Route to Next.js Router**: - ```javascript - // next.config.js - module.exports = { - async rewrites() { - return [ - { - source: '/custom-route', - destination: '/custom', - }, - ]; - }, - }; - ``` - -#### Route-Level Code Splitting - -Route-level code splitting ensures that only the necessary code for the current route is loaded, improving performance by reducing the initial load time. - -1. **Implementing Route-Level Code Splitting**: - - Next.js automatically splits your code into separate bundles for each page. Each page only loads the necessary code when it is accessed. - - You can leverage dynamic imports to further enhance code splitting: - ```javascript - // pages/index.js - import dynamic from 'next/dynamic'; - - const DynamicComponent = dynamic(() => import('../components/DynamicComponent')); - - export default function Home() { - return ( -
-

Home Page

- -
- ); - } - ``` - -2. **Using `dynamic` for Code Splitting with Custom Loading**: - ```javascript - // pages/index.js - import dynamic from 'next/dynamic'; - - const DynamicComponentWithCustomLoading = dynamic(() => import('../components/DynamicComponent'), { - loading: () =>

Loading...

, - }); - - export default function Home() { - return ( -
-

Home Page

- -
- ); - } - ``` - \ No newline at end of file diff --git a/courses/Next.Js/advance-level/Advance-Routing/Dynamic-Route.md b/courses/Next.Js/advance-level/Advance-Routing/Dynamic-Route.md deleted file mode 100644 index a0c3b3c73..000000000 --- a/courses/Next.Js/advance-level/Advance-Routing/Dynamic-Route.md +++ /dev/null @@ -1,80 +0,0 @@ ---- -id: lesson-1 -title: "Advanced Routing Techniques in Next.js" -sidebar_label: Advanced Routing Techniques -sidebar_position: 1 -description: "Advanced Routing Techniques in Next.js" -tags: [courses,Advance-level,FramWorks,Introduction] ---- - - -Advanced routing techniques in Next.js enable you to build more flexible and optimized applications. These techniques include dynamic API routes, middleware for route protection and redirects, customizing the Next.js router, and implementing route-level code splitting. - -#### Dynamic API Routes - -Dynamic API routes allow you to create API endpoints that can handle dynamic parameters. - -1. **Creating Dynamic API Routes**: - ```javascript - // pages/api/user/[id].js - export default function handler(req, res) { - const { - query: { id }, - method, - } = req; - - switch (method) { - case 'GET': - // Fetch user data - res.status(200).json({ id, name: `User ${id}` }); - break; - case 'PUT': - // Update user data - res.status(200).json({ id, name: `Updated User ${id}` }); - break; - default: - res.setHeader('Allow', ['GET', 'PUT']); - res.status(405).end(`Method ${method} Not Allowed`); - break; - } - } - ``` - -#### Middleware for Route Protection and Redirects - -Middleware can be used to protect routes and handle redirects based on certain conditions, such as user authentication. - -1. **Implementing Middleware for Route Protection**: - ```javascript - // middleware.js - import { NextResponse } from 'next/server'; - - export function middleware(req) { - const { pathname } = req.nextUrl; - - // Protect routes starting with /admin - if (pathname.startsWith('/admin')) { - const token = req.cookies.get('token'); - - if (!token) { - return NextResponse.redirect('/login'); - } - } - - return NextResponse.next(); - } - ``` - -2. **Adding Middleware to the Next.js Configuration**: - ```javascript - // next.config.js - module.exports = { - async rewrites() { - return { - beforeFiles: [ - { source: '/admin/:path*', destination: '/middleware' }, - ], - }; - }, - }; - ``` \ No newline at end of file diff --git a/courses/Next.Js/advance-level/Advance-Routing/_category_.json b/courses/Next.Js/advance-level/Advance-Routing/_category_.json deleted file mode 100644 index f437e3cd3..000000000 --- a/courses/Next.Js/advance-level/Advance-Routing/_category_.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "label": "Advanced Routing", - "position": 2, - "link": { - "type": "generated-index", - "description": "Learn Next.Js Advance Routing Techniques." - } - } \ No newline at end of file diff --git a/courses/Next.Js/advance-level/Advance-data-fetching/_category_.json b/courses/Next.Js/advance-level/Advance-data-fetching/_category_.json deleted file mode 100644 index 8e35b9b57..000000000 --- a/courses/Next.Js/advance-level/Advance-data-fetching/_category_.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "label": "Advanced Data Fetching", - "position": 1, - "link": { - "type": "generated-index", - "description": "Learn Next.Js Advanced Data Fetching." - } - } \ No newline at end of file diff --git a/courses/Next.Js/advance-level/Advance-data-fetching/dynamic-generation.md b/courses/Next.Js/advance-level/Advance-data-fetching/dynamic-generation.md deleted file mode 100644 index 6568debed..000000000 --- a/courses/Next.Js/advance-level/Advance-data-fetching/dynamic-generation.md +++ /dev/null @@ -1,122 +0,0 @@ ---- -id: lesson-2 -title: "Combining Static and Dynamic Data Fetching" -sidebar_label: Combining Static and Dynamic Data Fetching -sidebar_position: 2 -description: "Combining Static and Dynamic Data Fetching" -tags: [courses,Advance-level,FramWorks,Introduction] ---- - - -You can combine static and dynamic data fetching to build more flexible and performant applications. - -1. **Combining Static Generation with Client-side Fetching**: - ```javascript - // pages/index.js - import { useEffect, useState } from 'react'; - - export async function getStaticProps() { - // Fetch static data - const res = await fetch('https://api.example.com/static-data'); - const staticData = await res.json(); - - return { - props: { - staticData, - }, - revalidate: 60, // Revalidate every 60 seconds - }; - } - - export default function Home({ staticData }) { - const [dynamicData, setDynamicData] = useState(null); - - useEffect(() => { - // Fetch dynamic data on client-side - fetch('https://api.example.com/dynamic-data') - .then((res) => res.json()) - .then((data) => setDynamicData(data)); - }, []); - - return ( -
-

Combining Static and Dynamic Data Fetching

-

Static Data

-
{JSON.stringify(staticData, null, 2)}
-

Dynamic Data

- {dynamicData ? ( -
{JSON.stringify(dynamicData, null, 2)}
- ) : ( -

Loading...

- )} -
- ); - } - ``` - -#### Optimizing Data Fetching for Performance - -1. **Minimizing API Calls**: - - Cache data at various levels (CDN, server, client) to minimize API calls. - - Use tools like `SWR` or `React Query` to manage caching and synchronization of data. - -2. **Using Incremental Static Regeneration (ISR)**: - - ISR allows pages to be regenerated incrementally without rebuilding the entire site. - ```javascript - // pages/index.js - export async function getStaticProps() { - const res = await fetch('https://api.example.com/data'); - const data = await res.json(); - - return { - props: { - data, - }, - revalidate: 60, // Revalidate every 60 seconds - }; - } - - export default function Home({ data }) { - return ( -
-

Optimized Data Fetching

-
{JSON.stringify(data, null, 2)}
-
- ); - } - ``` - -3. **Prefetching Data**: - - Prefetch data for links using the `next/link` component to improve navigation speed. - ```javascript - import Link from 'next/link'; - - export default function Home() { - return ( -
-

Home Page

- - Go to About - -
- ); - } - ``` - -4. **Using SWR for Client-side Caching**: - - `SWR` (Stale-While-Revalidate) is a React Hooks library for data fetching that provides caching and revalidation. - ```javascript - import useSWR from 'swr'; - - const fetcher = (url) => fetch(url).then((res) => res.json()); - - export default function DataComponent() { - const { data, error } = useSWR('/api/data', fetcher); - - if (error) return
Failed to load
; - if (!data) return
Loading...
; - - return
Data: {JSON.stringify(data)}
; - } - ``` - \ No newline at end of file diff --git a/courses/Next.Js/advance-level/Advance-data-fetching/static-generation.md b/courses/Next.Js/advance-level/Advance-data-fetching/static-generation.md deleted file mode 100644 index 65e5341c7..000000000 --- a/courses/Next.Js/advance-level/Advance-data-fetching/static-generation.md +++ /dev/null @@ -1,76 +0,0 @@ ---- -id: lesson-1 -title: "Advanced Data Fetching in Next.js" -sidebar_label: Advanced Data Fetching in Next.js -sidebar_position: 1 -description: "Advanced Data Fetching in Next.js" -tags: [courses,Advance-level,FramWorks,Introduction] ---- - - - -Next.js provides powerful data fetching capabilities to optimize the performance and scalability of your application. This involves using static generation with revalidation, server-side rendering with caching strategies, combining static and dynamic data fetching, and optimizing these processes for performance. - -#### Static Generation with Revalidation - -Static generation with revalidation allows you to generate static pages at build time and update them at runtime when necessary. - -1. **Setting up Static Generation with Revalidation**: - ```javascript - // pages/index.js - export async function getStaticProps() { - // Fetch data - const res = await fetch('https://api.example.com/data'); - const data = await res.json(); - - return { - props: { - data, - }, - revalidate: 10, // Revalidate every 10 seconds - }; - } - - export default function Home({ data }) { - return ( -
-

Static Generation with Revalidation

-
{JSON.stringify(data, null, 2)}
-
- ); - } - ``` - -#### Server-side Rendering with Caching Strategies - -Server-side rendering (SSR) can be optimized using caching strategies to improve performance and reduce server load. - -1. **Setting up Server-side Rendering with Caching**: - ```javascript - // pages/ssr.js - export async function getServerSideProps(context) { - const res = await fetch('https://api.example.com/data'); - const data = await res.json(); - - context.res.setHeader('Cache-Control', 's-maxage=10, stale-while-revalidate'); - - return { - props: { - data, - }, - }; - } - - export default function SSR({ data }) { - return ( -
-

Server-side Rendering with Caching

-
{JSON.stringify(data, null, 2)}
-
- ); - } - ``` - -2. **Using Cache-Control Headers**: - - `s-maxage=10`: Cache the response on the server for 10 seconds. - - `stale-while-revalidate`: Serve stale content while revalidating in the background. \ No newline at end of file diff --git a/courses/Next.Js/advance-level/Advance-server-side-render/SSR.md b/courses/Next.Js/advance-level/Advance-server-side-render/SSR.md deleted file mode 100644 index d6a40f93f..000000000 --- a/courses/Next.Js/advance-level/Advance-server-side-render/SSR.md +++ /dev/null @@ -1,160 +0,0 @@ ---- -id: lesson-2 -title: "Optimizing SSR for Performance" -sidebar_label: Optimizing SSR -sidebar_position: 2 -description: "Optimizing SSR for Performance" -tags: [courses,Advance-level,FramWorks,Introduction] ---- - - - -1. **Caching Responses**: - - Use caching strategies to reduce the load on the server. - ```javascript - // pages/index.js - export async function getServerSideProps(context) { - const cache = new Map(); - const cacheKey = 'data'; - - if (cache.has(cacheKey)) { - return { - props: { - data: cache.get(cacheKey), - }, - }; - } - - const res = await fetch('https://api.example.com/data'); - const data = await res.json(); - cache.set(cacheKey, data); - - return { - props: { - data, - }, - }; - } - ``` - -2. **Optimizing Data Fetching**: - - Fetch only necessary data and minimize the amount of data sent to the client. - ```javascript - // pages/index.js - export async function getServerSideProps(context) { - const res = await fetch('https://api.example.com/data?fields=id,name'); - const data = await res.json(); - - return { - props: { - data, - }, - }; - } - ``` - -3. **Using Static Generation with Revalidation**: - - Use static generation with incremental static regeneration (ISR) for frequently updated data. - ```javascript - // pages/index.js - export async function getStaticProps() { - const res = await fetch('https://api.example.com/data'); - const data = await res.json(); - - return { - props: { - data, - }, - revalidate: 60, // Revalidate every 60 seconds - }; - } - - export default function Home({ data }) { - return ( -
-

Data with ISR

-
{JSON.stringify(data, null, 2)}
-
- ); - } - ``` - -#### SSR with Authentication and Session Management - -1. **Implementing Authentication**: - - Use a library like `next-auth` to handle authentication. - ```bash - npm install next-auth - ``` - - ```javascript - // pages/api/auth/[...nextauth].js - import NextAuth from 'next-auth'; - import Providers from 'next-auth/providers'; - - export default NextAuth({ - providers: [ - Providers.Google({ - clientId: process.env.GOOGLE_CLIENT_ID, - clientSecret: process.env.GOOGLE_CLIENT_SECRET, - }), - ], - }); - ``` - -2. **Protecting Routes**: - - Use `getServerSideProps` to check authentication status. - ```javascript - // pages/secure-page.js - import { getSession } from 'next-auth/react'; - - export async function getServerSideProps(context) { - const session = await getSession(context); - - if (!session) { - return { - redirect: { - destination: '/api/auth/signin', - permanent: false, - }, - }; - } - - return { - props: { session }, - }; - } - - export default function SecurePage({ session }) { - return ( -
-

Secure Page

-

Welcome, {session.user.name}!

-
- ); - } - ``` - -3. **Session Management**: - - Manage sessions using cookies or tokens. - ```javascript - // lib/auth.js - import { parseCookies, setCookie, destroyCookie } from 'nookies'; - - export function getAuthCookie(context) { - const cookies = parseCookies(context); - return cookies.auth; - } - - export function setAuthCookie(context, token) { - setCookie(context, 'auth', token, { - maxAge: 30 * 24 * 60 * 60, - path: '/', - }); - } - - export function destroyAuthCookie(context) { - destroyCookie(context, 'auth'); - } - ``` - \ No newline at end of file diff --git a/courses/Next.Js/advance-level/Advance-server-side-render/_category_.json b/courses/Next.Js/advance-level/Advance-server-side-render/_category_.json deleted file mode 100644 index ac7ed71b4..000000000 --- a/courses/Next.Js/advance-level/Advance-server-side-render/_category_.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "label": "Advanced Server-side Rendering", - "position": 4, - "link": { - "type": "generated-index", - "description": "Learn Advanced Server-side Rendering." - } - } \ No newline at end of file diff --git a/courses/Next.Js/advance-level/Advance-server-side-render/customize.md b/courses/Next.Js/advance-level/Advance-server-side-render/customize.md deleted file mode 100644 index 457ae489f..000000000 --- a/courses/Next.Js/advance-level/Advance-server-side-render/customize.md +++ /dev/null @@ -1,142 +0,0 @@ ---- -id: lesson-1 -title: "Advanced Server-Side Rendering (SSR) in Next.js" -sidebar_label: Advanced SSR -sidebar_position: 1 -description: "Advanced Server-Side Rendering (SSR) in Next.js" -tags: [courses,Advance-level,FramWorks,Introduction] ---- - - -Server-Side Rendering (SSR) in Next.js allows for dynamic data fetching and rendering on the server, providing a performant and SEO-friendly experience. This guide covers customizing the SSR process, handling complex data fetching and state management, optimizing SSR for performance, and implementing SSR with authentication and session management. - -#### Customizing the Server-Side Rendering Process - -1. **Customizing `getServerSideProps`**: - - Use `getServerSideProps` to fetch data on each request. - ```javascript - // pages/index.js - export async function getServerSideProps(context) { - const res = await fetch('https://api.example.com/data'); - const data = await res.json(); - - return { - props: { - data, - }, - }; - } - - export default function Home({ data }) { - return ( -
-

Data from Server

-
{JSON.stringify(data, null, 2)}
-
- ); - } - ``` - -2. **Handling Complex Data Fetching**: - - Perform multiple data fetches or handle errors within `getServerSideProps`. - ```javascript - // pages/index.js - export async function getServerSideProps(context) { - try { - const [res1, res2] = await Promise.all([ - fetch('https://api.example.com/data1'), - fetch('https://api.example.com/data2'), - ]); - const data1 = await res1.json(); - const data2 = await res2.json(); - - return { - props: { - data1, - data2, - }, - }; - } catch (error) { - return { - props: { - error: 'Failed to fetch data', - }, - }; - } - } - - export default function Home({ data1, data2, error }) { - if (error) { - return

{error}

; - } - - return ( -
-

Data from Server

-
{JSON.stringify(data1, null, 2)}
-
{JSON.stringify(data2, null, 2)}
-
- ); - } - ``` - -#### Handling Complex Data Fetching and State Management - -1. **Integrating Redux with SSR**: - - Set up Redux store and integrate with `getServerSideProps`. - ```javascript - // store.js - import { createStore } from 'redux'; - import rootReducer from './reducers'; - - export const initializeStore = (preloadedState) => { - return createStore(rootReducer, preloadedState); - }; - ``` - - ```javascript - // pages/_app.js - import { Provider } from 'react-redux'; - import { initializeStore } from '../store'; - - export default function App({ Component, pageProps }) { - const store = initializeStore(pageProps.initialReduxState); - - return ( - - - - ); - } - ``` - - ```javascript - // pages/index.js - import { useSelector } from 'react-redux'; - import { initializeStore } from '../store'; - import { fetchData } from '../actions'; - - export async function getServerSideProps() { - const reduxStore = initializeStore(); - const { dispatch } = reduxStore; - - await dispatch(fetchData()); - - return { - props: { - initialReduxState: reduxStore.getState(), - }, - }; - } - - export default function Home() { - const data = useSelector((state) => state.data); - - return ( -
-

Data from Redux Store

-
{JSON.stringify(data, null, 2)}
-
- ); - } - ``` \ No newline at end of file diff --git a/courses/Next.Js/advance-level/GraphQL/Introduction.md b/courses/Next.Js/advance-level/GraphQL/Introduction.md deleted file mode 100644 index 565f99fe3..000000000 --- a/courses/Next.Js/advance-level/GraphQL/Introduction.md +++ /dev/null @@ -1,106 +0,0 @@ ---- -id: lesson-1 -title: "Next.js and GraphQL" -sidebar_label: GraphQL -sidebar_position: 1 -description: "Next.js and GraphQL" -tags: [courses,Advance-level,FramWorks,Introduction] ---- - - -Integrating GraphQL with Next.js allows you to leverage the powerful capabilities of GraphQL for querying data while enjoying the benefits of Next.js, such as server-side rendering and static site generation. Here's a guide to setting up a GraphQL server with Next.js, querying GraphQL APIs from Next.js, using Apollo Client, and advanced GraphQL features. - -#### Setting up a GraphQL Server with Next.js - -1. **Install Required Packages**: - ```bash - npm install apollo-server-micro graphql - ``` - -2. **Create a GraphQL Server**: - ```javascript - // pages/api/graphql.js - import { ApolloServer, gql } from 'apollo-server-micro'; - - const typeDefs = gql` - type Query { - hello: String - } - `; - - const resolvers = { - Query: { - hello: () => 'Hello, world!', - }, - }; - - const apolloServer = new ApolloServer({ typeDefs, resolvers }); - - export const config = { - api: { - bodyParser: false, - }, - }; - - const startServer = apolloServer.start(); - - export default async function handler(req, res) { - await startServer; - await apolloServer.createHandler({ path: '/api/graphql' })(req, res); - } - ``` - -3. **Test the GraphQL Server**: - - Start your Next.js development server and navigate to `/api/graphql`. - - Use a tool like GraphQL Playground or Insomnia to send queries to your GraphQL endpoint. - -#### Querying GraphQL APIs from Next.js - -1. **Install Apollo Client**: - ```bash - npm install @apollo/client graphql - ``` - -2. **Set up Apollo Client**: - ```javascript - // lib/apolloClient.js - import { ApolloClient, InMemoryCache } from '@apollo/client'; - - const client = new ApolloClient({ - uri: '/api/graphql', - cache: new InMemoryCache(), - }); - - export default client; - ``` - -3. **Query GraphQL APIs in a Next.js Page**: - ```javascript - // pages/index.js - import { gql } from '@apollo/client'; - import client from '../lib/apolloClient'; - - export async function getStaticProps() { - const { data } = await client.query({ - query: gql` - query { - hello - } - `, - }); - - return { - props: { - message: data.hello, - }, - }; - } - - export default function Home({ message }) { - return ( -
-

{message}

-
- ); - } - ``` \ No newline at end of file diff --git a/courses/Next.Js/advance-level/GraphQL/_category_.json b/courses/Next.Js/advance-level/GraphQL/_category_.json deleted file mode 100644 index f21c26ee3..000000000 --- a/courses/Next.Js/advance-level/GraphQL/_category_.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "label": "Next.js and GraphQL", - "position": 3, - "link": { - "type": "generated-index", - "description": "Learn Next.Js and GraphQL." - } - } \ No newline at end of file diff --git a/courses/Next.Js/advance-level/GraphQL/apollo-client.md b/courses/Next.Js/advance-level/GraphQL/apollo-client.md deleted file mode 100644 index c073cf05c..000000000 --- a/courses/Next.Js/advance-level/GraphQL/apollo-client.md +++ /dev/null @@ -1,226 +0,0 @@ ---- -id: lesson-2 -title: "Using Apollo Client with Next.js" -sidebar_label: Apollo Client -sidebar_position: 2 -description: "Using Apollo Client with Next.js" -tags: [courses,Advance-level,FramWorks,Introduction] ---- - - -1. **Create an Apollo Provider**: - ```javascript - // lib/apolloClient.js - import { ApolloClient, InMemoryCache, ApolloProvider } from '@apollo/client'; - - const client = new ApolloClient({ - uri: '/api/graphql', - cache: new InMemoryCache(), - }); - - export function ApolloProviderWrapper({ children }) { - return {children}; - } - ``` - -2. **Wrap the App Component**: - ```javascript - // pages/_app.js - import { ApolloProviderWrapper } from '../lib/apolloClient'; - - function MyApp({ Component, pageProps }) { - return ( - - - - ); - } - - export default MyApp; - ``` - -3. **Query Data in Components**: - ```javascript - // components/Hello.js - import { useQuery, gql } from '@apollo/client'; - - const HELLO_QUERY = gql` - query { - hello - } - `; - - export default function Hello() { - const { loading, error, data } = useQuery(HELLO_QUERY); - - if (loading) return

Loading...

; - if (error) return

Error: {error.message}

; - - return

{data.hello}

; - } - ``` - -4. **Use the Component**: - ```javascript - // pages/index.js - import Hello from '../components/Hello'; - - export default function Home() { - return ( -
- -
- ); - } - ``` - -#### Advanced GraphQL Features (Subscriptions, Caching) - -1. **Setting Up Subscriptions**: - - For subscriptions, you need to set up a WebSocket server. First, install the required packages: - ```bash - npm install subscriptions-transport-ws @apollo/client graphql-ws - ``` - - - Configure your Apollo Server to support subscriptions: - ```javascript - // pages/api/graphql.js - import { ApolloServer, gql } from 'apollo-server-micro'; - import { useServer } from 'graphql-ws/lib/use/ws'; - import { WebSocketServer } from 'ws'; - - const typeDefs = gql` - type Query { - hello: String - } - type Subscription { - time: String - } - `; - - const resolvers = { - Query: { - hello: () => 'Hello, world!', - }, - Subscription: { - time: { - subscribe: (_, __, { pubsub }) => { - setInterval(() => pubsub.publish('TIME', { time: new Date().toISOString() }), 1000); - return pubsub.asyncIterator('TIME'); - }, - }, - }, - }; - - const pubsub = new PubSub(); - const apolloServer = new ApolloServer({ typeDefs, resolvers, context: { pubsub } }); - - export const config = { - api: { - bodyParser: false, - }, - }; - - const startServer = apolloServer.start(); - - export default async function handler(req, res) { - await startServer; - await apolloServer.createHandler({ path: '/api/graphql' })(req, res); - } - - // Setup WebSocket server - const wsServer = new WebSocketServer({ port: 4000 }); - useServer({ schema: apolloServer.schema }, wsServer); - ``` - - - Connect to the subscription server in your client: - ```javascript - // lib/apolloClient.js - import { ApolloClient, InMemoryCache, ApolloProvider, split } from '@apollo/client'; - import { WebSocketLink } from '@apollo/client/link/ws'; - import { createHttpLink } from '@apollo/client'; - import { getMainDefinition } from '@apollo/client/utilities'; - - const httpLink = createHttpLink({ - uri: '/api/graphql', - }); - - const wsLink = new WebSocketLink({ - uri: 'ws://localhost:4000/graphql', - options: { - reconnect: true, - }, - }); - - const splitLink = split( - ({ query }) => { - const definition = getMainDefinition(query); - return ( - definition.kind === 'OperationDefinition' && definition.operation === 'subscription' - ); - }, - wsLink, - httpLink - ); - - const client = new ApolloClient({ - link: splitLink, - cache: new InMemoryCache(), - }); - - export function ApolloProviderWrapper({ children }) { - return {children}; - } - ``` - - - Use subscriptions in your component: - ```javascript - // components/Time.js - import { useSubscription, gql } from '@apollo/client'; - - const TIME_SUBSCRIPTION = gql` - subscription { - time - } - `; - - export default function Time() { - const { data, loading } = useSubscription(TIME_SUBSCRIPTION); - - if (loading) return

Loading...

; - - return

Current time: {data.time}

; - } - ``` - -2. **Optimizing Caching with Apollo Client**: - - Configure cache policies in Apollo Client: - ```javascript - // lib/apolloClient.js - import { ApolloClient, InMemoryCache, ApolloProvider } from '@apollo/client'; - - const client = new ApolloClient({ - uri: '/api/graphql', - cache: new InMemoryCache({ - typePolicies: { - Query: { - fields: { - hello: { - read(existing) { - return existing; - }, - }, - }, - }, - }, - }), - }); - - export function ApolloProviderWrapper({ children }) { - return {children}; - } - ``` - -3. **Using Advanced GraphQL Features**: - - Utilize Apollo Client's built-in features for caching, pagination, optimistic UI updates, etc. - - Refer to Apollo Client documentation for detailed examples and advanced use cases: [Apollo Client Docs](https://www.apollographql.com/docs/react/) \ No newline at end of file diff --git a/courses/Next.Js/advance-level/_category_.json b/courses/Next.Js/advance-level/_category_.json deleted file mode 100644 index cd2d95485..000000000 --- a/courses/Next.Js/advance-level/_category_.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "label": "Advanced Level", - "position": 3, - "link": { - "type": "generated-index", - "description": "Learn Next.Js Advance Techniques." - } - } \ No newline at end of file diff --git a/courses/Next.Js/beginner-level/Introduction/Frameworks.md b/courses/Next.Js/beginner-level/Introduction/Frameworks.md deleted file mode 100644 index 2d939dde9..000000000 --- a/courses/Next.Js/beginner-level/Introduction/Frameworks.md +++ /dev/null @@ -1,65 +0,0 @@ ---- -id: lesson-2 -title: "Comparing Next.js with Other Frameworks" -sidebar_label: Next.js with Frameworks -sidebar_position: 2 -description: "Comparing Next.js with Other Frameworks" -tags: [courses, beginner-level, FramWorks, Introduction] ---- - -## Comparing Next.js with Other Frameworks - -### 1. Next.js vs. React - -- **React**: A library for building user interfaces. It focuses on the view layer and requires additional libraries and tools for routing, state management, and server-side rendering. -- **Next.js**: A framework built on top of React that provides out-of-the-box features like SSR, SSG, and file-based routing. It simplifies the setup and development process for React applications. - -### 2. Next.js vs. Angular - -- **Angular**: A full-fledged framework developed by Google that includes a complete set of tools for building single-page applications. It uses TypeScript by default and has a more opinionated structure. -- **Next.js**: Focuses on server-side rendering and static site generation for React applications. It is less opinionated than Angular and provides more flexibility in terms of tools and libraries. - -### 3. Next.js vs. Vue - -- **Vue**: A progressive framework for building user interfaces, similar to React in terms of component-based architecture. -- **Nuxt.js**: A framework built on top of Vue that provides similar features to Next.js, including SSR and SSG. -- **Next.js**: The React counterpart to Nuxt.js, providing SSR, SSG, and additional optimizations for React applications. - -### 4. Next.js vs. Gatsby - -- **Gatsby**: A static site generator that uses React to build websites. It focuses on performance, SEO, and developer experience. -- **Next.js**: Offers similar features to Gatsby, such as SSR and SSG, but with more flexibility and control over the development process. It is more suitable for applications that require server-side logic and dynamic data fetching. - -### 5. Next.js vs. SvelteKit - -- **SvelteKit**: A framework for building web applications using the Svelte framework. It focuses on simplicity, performance, and developer experience. -- **Next.js**: Offers similar features to SvelteKit, such as SSR and SSG, but with a React-based approach. It provides a rich ecosystem of tools and libraries for building modern web applications. - -### 6. Next.js vs. Express (Node.js) - -- **Express**: A minimalist web framework for Node.js that focuses on building server-side applications and APIs. -- **Next.js**: A framework for building React applications with server-side rendering and static site generation. It provides additional features like automatic code splitting, API routes, and optimized performance. - -### 7. Next.js vs. Nuxt.js - -- **Nuxt.js**: A framework for building Vue applications with server-side rendering and static site generation. -- **Next.js**: The React counterpart to Nuxt.js, providing similar features like SSR, SSG, and a rich ecosystem of tools and libraries for building modern web applications. - -### 8. Next.js vs. Create React App (CRA) - -- **Create React App**: A tool for setting up React applications with a predefined configuration and build process. -- **Next.js**: A framework that extends React with features like SSR, SSG, and API routes. It provides a more structured approach to building React applications with additional optimizations for performance and developer experience. - -### 9. Next.js vs. Blitz.js - -- **Blitz.js**: A full-stack framework for building web applications with React and Prisma. It focuses on developer productivity and seamless integration of backend and frontend logic. -- **Next.js**: Offers similar features to Blitz.js, such as SSR and SSG, but with a more flexible approach to building applications. It provides a broader range of tools and libraries for customizing and optimizing React applications. - -### 10. Next.js vs. Sapper - -- **Sapper**: A framework for building web applications with Svelte that includes features like server-side rendering and routing. -- **Next.js**: Offers similar features to Sapper, such as SSR and SSG, but with a React-based approach. It provides a more extensive set of tools and optimizations for building React applications. - -### Conclusion - -Next.js is a powerful framework for building React applications with server-side rendering, static site generation, and a rich ecosystem of tools and libraries. While there are other frameworks available for building web applications, Next.js stands out for its performance, developer experience, and flexibility in handling various use cases. Whether you are building a simple website, a full-fledged web application, or a complex enterprise solution, Next.js provides the features and optimizations needed to deliver high-quality applications efficiently. diff --git a/courses/Next.Js/beginner-level/Introduction/_category_.json b/courses/Next.Js/beginner-level/Introduction/_category_.json deleted file mode 100644 index 713020a21..000000000 --- a/courses/Next.Js/beginner-level/Introduction/_category_.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "label": "Introduction", - "position": 1, - "link": { - "type": "generated-index", - "description": "Let's Start with Next.Js." - } - } \ No newline at end of file diff --git a/courses/Next.Js/beginner-level/Introduction/introduction.md b/courses/Next.Js/beginner-level/Introduction/introduction.md deleted file mode 100644 index 9baba51c8..000000000 --- a/courses/Next.Js/beginner-level/Introduction/introduction.md +++ /dev/null @@ -1,67 +0,0 @@ ---- -id: lesson-1 -title: Introduction to Next.js -sidebar_label: Introduction -sidebar_position: 1 -description: Introduction to Next.js -tags: [courses, beginner-level, FramWorks, Introduction] ---- - -## What is Next.js? - -**Next.js** is a React framework that enables server-side rendering and static site generation for React applications. Developed by Vercel, it aims to provide a seamless developer experience while enhancing performance, scalability, and SEO. Next.js builds on top of React and provides a number of additional features to improve the development process and application performance. - -:::note - -Next.js offers several key features that make it a popular choice for building React applications: - -1. **Server-Side Rendering (SSR)**: Next.js enables server-side rendering, which allows pages to be pre-rendered on the server and sent to the client as fully rendered HTML. This improves initial load times and SEO. - -2. **Static Site Generation (SSG)**: Next.js can generate static HTML at build time for pages that don't need to be rendered on every request. This results in fast load times and efficient performance. - -3. **Automatic Code Splitting**: Next.js automatically splits code into smaller bundles that are loaded only when needed, optimizing page load times and performance. - -4. **API Routes**: Next.js allows you to create API endpoints within the same application, simplifying the process of building full-stack applications. - -5. **Optimized Performance**: With features like automatic static optimization, image optimization, and lazy loading, Next.js applications are highly performant. - -6. **Built-in CSS and Sass Support**: Next.js has built-in support for importing CSS and Sass files, making it easy to style your applications. - -7. **Developer Experience**: Features like fast refresh, which provides instantaneous feedback on edits without losing component state, make the development process more efficient and enjoyable. - ::: - -## Why Learn Next.js? - -Learning Next.js offers several benefits for developers looking to build modern web applications: - -1. **Improved Performance**: Next.js provides server-side rendering and static site generation, resulting in faster load times and better SEO performance. -2. **Enhanced SEO**: Pre-rendered pages in Next.js improve search engine optimization by providing search engines with fully rendered HTML content. -3. **Simplified Development**: Next.js simplifies the development process by offering features like automatic code splitting, API routes, and built-in CSS support. -4. **Scalability**: Next.js applications are highly scalable and can handle increased traffic and data requirements effectively. -5. **Full-Stack Development**: Next.js allows developers to build full-stack applications by integrating API routes and server-side rendering with React components. -6. **Community and Ecosystem**: Next.js has a vibrant community and ecosystem, with extensive documentation, tutorials, and plugins available to support developers. -7. **Career Opportunities**: Learning Next.js can open up career opportunities as Next.js developers are in demand due to the framework's popularity and versatility. -8. **Modern Web Development**: Next.js is a modern framework that incorporates the latest web development practices and tools, making it a valuable skill for developers. -9. **Vercel Integration**: Next.js is developed by Vercel, which offers hosting and deployment services that seamlessly integrate with Next.js applications. -10. **React Compatibility**: Next.js is built on top of React, making it a natural choice for developers familiar with React who want to enhance their applications with server-side rendering and static site generation. -11. **Performance Monitoring**: Next.js provides built-in performance monitoring tools that help developers optimize their applications for speed and efficiency. -12. **Incremental Static Regeneration**: Next.js supports incremental static regeneration, allowing developers to update static pages without requiring a full rebuild of the site. -13. **Hybrid Static and Server-Side Rendering**: Next.js allows developers to combine static site generation with server-side rendering for optimal performance and flexibility. -14. **TypeScript Support**: Next.js has built-in support for TypeScript, enabling developers to write type-safe code and improve code quality and maintainability. -15. **Internationalization**: Next.js provides built-in support for internationalization, making it easy to create multilingual applications with localized content. -16. **Authentication and Authorization**: Next.js offers solutions for implementing authentication and authorization in applications, ensuring secure access to resources and data. -17. **Testing and Debugging**: Next.js provides tools and utilities for testing and debugging applications, helping developers ensure the quality and reliability of their code. -18. **Continuous Integration and Deployment**: Next.js applications can be easily integrated with CI/CD pipelines for automated testing, building, and deployment processes. -19. **Serverless Functions**: Next.js allows developers to create serverless functions that can be deployed alongside their applications, enabling server-side logic without managing servers. -20. **Data Fetching Strategies**: Next.js supports various data fetching strategies, including `getStaticProps`, `getServerSideProps`, and `useSWR`, to fetch data at build time or on each request. -21. **Error Handling**: Next.js provides error handling mechanisms that help developers identify and resolve issues in their applications, ensuring a smooth user experience. -22. **Optimized Image Loading**: Next.js offers optimized image loading techniques, such as automatic image optimization and lazy loading, to improve performance and reduce bandwidth usage. -23. **SEO Metadata**: Next.js allows developers to define SEO metadata for pages, including titles, descriptions, and Open Graph tags, to enhance search engine visibility and social sharing. -24. **Accessibility**: Next.js promotes accessibility best practices by providing tools and guidelines for creating inclusive web applications that are usable by all users. -25. **Documentation and Support**: Next.js has comprehensive documentation and community support, making it easy for developers to learn and troubleshoot issues while building applications. - -By learning Next.js, developers can leverage these features and benefits to create high-performance, scalable, and modern web applications that meet the demands of today's digital landscape. - -## Conclusion - -Next.js is a powerful React framework that offers server-side rendering, static site generation, and a range of features to enhance the development process and application performance. By learning Next.js, developers can build fast, scalable, and SEO-friendly web applications with a seamless developer experience. Whether you are new to web development or looking to enhance your existing skills, Next.js provides a valuable toolkit for creating modern web applications that deliver exceptional user experiences. diff --git a/courses/Next.Js/beginner-level/Introduction/settingUp.md b/courses/Next.Js/beginner-level/Introduction/settingUp.md deleted file mode 100644 index c08ea88e5..000000000 --- a/courses/Next.Js/beginner-level/Introduction/settingUp.md +++ /dev/null @@ -1,65 +0,0 @@ ---- -id: lesson-3 -title: "Setting Up the Development Environment" -sidebar_label: Setup -sidebar_position: 3 -description: "Setting Up the Development Environment" -tags: [courses, beginner-level, FramWorks, Introduction] ---- - -To get started with Next.js, you'll need Node.js and npm (or yarn) installed on your system. Follow these steps to set up a Next.js development environment: - -1. **Install Node.js**: - - - Download and install Node.js from [nodejs.org](https://nodejs.org/). - -2. **Create a New Next.js Application**: - - - Open your terminal and run the following command to create a new Next.js project: - ```bash - npx create-next-app@latest my-next-app - # or - yarn create next-app my-next-app - ``` - -3. **Navigate to the Project Directory**: - - - Change to the project directory: - ```bash - cd my-next-app - ``` - -4. **Start the Development Server**: - - - Run the development server: - ```bash - npm run dev - # or - yarn dev - ``` - - Open your browser and navigate to [http://localhost:3000](http://localhost:3000) to see your Next.js application running. - -5. **Explore the Project Structure**: - - - Next.js projects have the following structure: - ``` - my-next-app/ - ├── .next/ # Build output - ├── node_modules/ # Node.js modules - ├── pages/ # Pages and routes - ├── public/ # Static assets - ├── styles/ # Global styles - ├── .gitignore # Git ignore file - ├── package.json # Project metadata - ├── README.md # Project README - ``` - -6. **Start Building Your Next.js Application**: - - - You're now ready to start building your Next.js application. Explore the project structure, create new pages, and customize your application as needed. - -By following these steps, you can set up a development environment for building Next.js applications and start creating modern web experiences with ease. Happy coding! - -## Additional Resources: - -- [Next.js Documentation](https://nextjs.org/docs) diff --git a/courses/Next.Js/beginner-level/Pages-and-routing/FIlebase-Routing.md b/courses/Next.Js/beginner-level/Pages-and-routing/FIlebase-Routing.md deleted file mode 100644 index 4100c1118..000000000 --- a/courses/Next.Js/beginner-level/Pages-and-routing/FIlebase-Routing.md +++ /dev/null @@ -1,80 +0,0 @@ ---- -id: lesson-2 -title: "Understanding the File-Based Routing System" -sidebar_label: File-Based Routing System -sidebar_position: 2 -description: "Understanding the File-Based Routing System" -tags: [courses,beginner-level,FramWorks,Introduction] ---- - - -Next.js uses a file-based routing system, where the file structure inside the `src/pages` directory defines the routes of the application. - -1. **File and Folder Structure**: - - Each file in `src/pages` represents a unique route based on its name and path. - - Folders within `src/pages` can contain additional pages and create nested routes. - -2. **Example Structure**: - ``` - src/pages/ - ├── about.js // Maps to /about - ├── index.js // Maps to / - ├── blog/ - │ ├── index.js // Maps to /blog - │ └── [id].js // Maps to /blog/:id - ├── contact.js // Maps to /contact - └── products/ - ├── index.js // Maps to /products - └── [id].js // Maps to /products/:id - ``` - -3. **Dynamic Routing**: - - Dynamic routes can be created using square brackets in the file name. For example, `[id].js` creates a dynamic route that matches any value in place of `id`: - ```javascript - // src/pages/blog/[id].js - import { useRouter } from 'next/router'; - - export default function BlogPost() { - const router = useRouter(); - const { id } = router.query; - - return

Blog Post {id}

; - } - ``` - - This file will be accessible at URLs like `/blog/1`, `/blog/2`, etc., where `1` and `2` are dynamic parameters. - -#### Nested Routes - -Nested routes can be achieved by creating folders within the `src/pages` directory and adding files within those folders. - -1. **Nested Route Example**: - - Create a `products` directory inside `src/pages`: - ``` - src/pages/products/ - ├── index.js // Maps to /products - └── [id].js // Maps to /products/:id - ``` - -2. **Nested Index Page**: - - The `index.js` file inside the `products` directory maps to the `/products` route: - ```javascript - // src/pages/products/index.js - export default function Products() { - return

Products Page

; - } - ``` - -3. **Nested Dynamic Route**: - - The `[id].js` file inside the `products` directory maps to dynamic routes like `/products/1`, `/products/2`, etc.: - ```javascript - // src/pages/products/[id].js - import { useRouter } from 'next/router'; - - export default function Product() { - const router = useRouter(); - const { id } = router.query; - - return

Product {id}

; - } - ``` - \ No newline at end of file diff --git a/courses/Next.Js/beginner-level/Pages-and-routing/_category_.json b/courses/Next.Js/beginner-level/Pages-and-routing/_category_.json deleted file mode 100644 index cb7010da8..000000000 --- a/courses/Next.Js/beginner-level/Pages-and-routing/_category_.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "label": "Pages and Routing", - "position": 3, - "link": { - "type": "generated-index", - "description": "Learn to Routing." - } - } \ No newline at end of file diff --git a/courses/Next.Js/beginner-level/Pages-and-routing/creating-pages.md b/courses/Next.Js/beginner-level/Pages-and-routing/creating-pages.md deleted file mode 100644 index aecf68588..000000000 --- a/courses/Next.Js/beginner-level/Pages-and-routing/creating-pages.md +++ /dev/null @@ -1,33 +0,0 @@ ---- -id: lesson-1 -title: "Pages and Routing in Next.js" -sidebar_label: Pages and Routing -sidebar_position: 1 -description: "Pages and Routing in Next.js" -tags: [courses,beginner-level,FramWorks,Introduction] ---- - - -#### Creating Pages in Next.js - -In Next.js, pages are React components that are stored in the `src/pages` directory. Each file in this directory corresponds to a route in the application. - -1. **Basic Page Creation**: - - To create a new page, add a new file to the `src/pages` directory. For example, to create an "About" page, create `src/pages/about.js`: - ```javascript - // src/pages/about.js - export default function About() { - return

About Us

; - } - ``` - - This file will be accessible at the `/about` URL. - -2. **Home Page**: - - The default home page is created by adding `index.js` to the `src/pages` directory: - ```javascript - // src/pages/index.js - export default function Home() { - return

Welcome to Our Site

; - } - ``` - - This file will be accessible at the root URL `/`. diff --git a/courses/Next.Js/beginner-level/Routes/Database.md b/courses/Next.Js/beginner-level/Routes/Database.md deleted file mode 100644 index 0f365fe7f..000000000 --- a/courses/Next.Js/beginner-level/Routes/Database.md +++ /dev/null @@ -1,120 +0,0 @@ ---- -id: lesson-2 -title: "Connecting API Routes to a Database" -sidebar_label: Database Connection -sidebar_position: 2 -description: "Connecting API Routes to a Database" -tags: [courses,beginner-level,FramWorks,Introduction] ---- - - -You can connect your API routes to a database using popular database libraries like `mongoose` for MongoDB or `prisma` for SQL databases. Below is an example using MongoDB and Mongoose. - -1. **Install Mongoose**: - ```bash - npm install mongoose - ``` - -2. **Create a Database Connection Helper**: - - Create a `src/lib/dbConnect.js` file to manage the database connection: - ```javascript - // src/lib/dbConnect.js - import mongoose from 'mongoose'; - - const MONGODB_URI = process.env.MONGODB_URI; - - if (!MONGODB_URI) { - throw new Error( - 'Please define the MONGODB_URI environment variable inside .env.local' - ); - } - - let cached = global.mongoose; - - if (!cached) { - cached = global.mongoose = { conn: null, promise: null }; - } - - async function dbConnect() { - if (cached.conn) { - return cached.conn; - } - - if (!cached.promise) { - const opts = { - useNewUrlParser: true, - useUnifiedTopology: true, - bufferCommands: false, - bufferMaxEntries: 0, - useFindAndModify: false, - useCreateIndex: true, - }; - - cached.promise = mongoose.connect(MONGODB_URI, opts).then((mongoose) => { - return mongoose; - }); - } - cached.conn = await cached.promise; - return cached.conn; - } - - export default dbConnect; - ``` - -3. **Create a Mongoose Model**: - - Create a `src/models/User.js` file for the User model: - ```javascript - // src/models/User.js - import mongoose from 'mongoose'; - - const UserSchema = new mongoose.Schema({ - name: { - type: String, - required: [true, 'Please provide a name'], - }, - email: { - type: String, - required: [true, 'Please provide an email'], - unique: true, - }, - }); - - export default mongoose.models.User || mongoose.model('User', UserSchema); - ``` - -4. **Use the Database in API Routes**: - - Update your API route to connect to the database and interact with the User model: - ```javascript - // src/pages/api/users.js - import dbConnect from '../../lib/dbConnect'; - import User from '../../models/User'; - - export default async function handler(req, res) { - const { method } = req; - - await dbConnect(); - - switch (method) { - case 'GET': - try { - const users = await User.find({}); - res.status(200).json({ success: true, data: users }); - } catch (error) { - res.status(400).json({ success: false, error }); - } - break; - case 'POST': - try { - const user = await User.create(req.body); - res.status(201).json({ success: true, data: user }); - } catch (error) { - res.status(400).json({ success: false, error }); - } - break; - default: - res.setHeader('Allow', ['GET', 'POST']); - res.status(405).end(`Method ${method} Not Allowed`); - } - } - ``` - \ No newline at end of file diff --git a/courses/Next.Js/beginner-level/Routes/Introduction.md b/courses/Next.Js/beginner-level/Routes/Introduction.md deleted file mode 100644 index 9ad05ac3c..000000000 --- a/courses/Next.Js/beginner-level/Routes/Introduction.md +++ /dev/null @@ -1,48 +0,0 @@ ---- -id: lesson-1 -title: "API Routes in Next.js" -sidebar_label: API Routes -sidebar_position: 1 -description: "API Routes in Next.js" -tags: [courses,beginner-level,FramWorks,Introduction] ---- - -Next.js provides a simple way to create API routes that you can use to handle backend logic, such as interacting with a database or performing server-side operations. These routes can be created within the `src/pages/api` directory. - -#### Creating API Routes in Next.js - -1. **Basic API Route**: - - Create a new file in the `src/pages/api` directory. For example, create `hello.js`: - ```javascript - // src/pages/api/hello.js - export default function handler(req, res) { - res.status(200).json({ message: 'Hello, world!' }); - } - ``` - - This API route will be accessible at `/api/hello`. - -2. **Handling API Requests**: - - API routes have access to the request (`req`) and response (`res`) objects, allowing you to handle different HTTP methods (GET, POST, PUT, DELETE, etc.). - -3. **Example with Multiple Methods**: - ```javascript - // src/pages/api/users.js - export default function handler(req, res) { - const { method } = req; - - switch (method) { - case 'GET': - // Handle GET request - res.status(200).json({ message: 'GET request' }); - break; - case 'POST': - // Handle POST request - const data = req.body; - res.status(201).json({ message: 'User created', data }); - break; - default: - res.setHeader('Allow', ['GET', 'POST']); - res.status(405).end(`Method ${method} Not Allowed`); - } - } - ``` diff --git a/courses/Next.Js/beginner-level/Routes/_category_.json b/courses/Next.Js/beginner-level/Routes/_category_.json deleted file mode 100644 index 8fb15c2a6..000000000 --- a/courses/Next.Js/beginner-level/Routes/_category_.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "label": "API Routes", - "position": 6, - "link": { - "type": "generated-index", - "description": "Learn Next.Js API Routes." - } - } \ No newline at end of file diff --git a/courses/Next.Js/beginner-level/Started/Running-development.md b/courses/Next.Js/beginner-level/Started/Running-development.md deleted file mode 100644 index 85e1e369d..000000000 --- a/courses/Next.Js/beginner-level/Started/Running-development.md +++ /dev/null @@ -1,64 +0,0 @@ ---- -id: lesson-2 -title: "Running the Development Server" -sidebar_label: Development Server -sidebar_position: 2 -description: "Learn Development Server" -tags: [courses,beginner-level,FramWorks,Introduction] ---- - - - -To run the development server and start your Next.js application: - -1. Navigate to the project directory: - ```bash - cd my-next-app - ``` - -2. Start the development server: - ```bash - npm run dev - # or - yarn dev - ``` - -3. Open your browser and navigate to [http://localhost:3000](http://localhost:3000). You should see your Next.js application running. - -#### Building and Deploying a Next.js App - -Next.js provides built-in commands to build and deploy your application. - -1. **Building the Application**: - - Run the following command to create an optimized production build: - ```bash - npm run build - # or - yarn build - ``` - - This will generate a `.next` directory containing the compiled application. - -2. **Starting the Production Server**: - - After building the application, you can start the production server: - ```bash - npm start - # or - yarn start - ``` - -3. **Deploying the Application**: - - **Vercel**: Vercel is the company behind Next.js and provides seamless integration for deploying Next.js applications. - - Install the Vercel CLI: - ```bash - npm install -g vercel - ``` - - Deploy your application: - ```bash - vercel - ``` - - Follow the prompts to link your project to a Vercel account and deploy it. - - - **Other Hosting Providers**: Next.js can be deployed on various hosting providers like AWS, Azure, Google Cloud, and DigitalOcean. - - Deploy the `.next` directory along with your project files to your preferred hosting provider. - - Ensure the environment supports Node.js and configure the start command to `npm start` or `yarn start`. - \ No newline at end of file diff --git a/courses/Next.Js/beginner-level/Started/_category_.json b/courses/Next.Js/beginner-level/Started/_category_.json deleted file mode 100644 index 33c4c33a0..000000000 --- a/courses/Next.Js/beginner-level/Started/_category_.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "label": "Project Build & Deployment", - "position": 2, - "link": { - "type": "generated-index", - "description": "Project Build & Deployment." - } - } \ No newline at end of file diff --git a/courses/Next.Js/beginner-level/Started/creating-project.md b/courses/Next.Js/beginner-level/Started/creating-project.md deleted file mode 100644 index 44ed25dda..000000000 --- a/courses/Next.Js/beginner-level/Started/creating-project.md +++ /dev/null @@ -1,67 +0,0 @@ ---- -id: lesson-1 -title: "Getting Started with Next.js" -sidebar_label: Understanding Project -sidebar_position: 1 -description: "Getting Started with Next.js" -tags: [courses,beginner-level,FramWorks,Introduction] ---- - - -#### Creating a New Next.js Project - -To create a new Next.js project, you'll need to have Node.js and npm (or yarn) installed on your system. Follow these steps to set up your project: - -1. **Install Node.js**: - - Download and install Node.js from [nodejs.org](https://nodejs.org/). - -2. **Create a New Next.js Application**: - - Open your terminal and run the following command to create a new Next.js project: - ```bash - npx create-next-app@latest my-next-app - # or - yarn create next-app my-next-app - ``` - - - This command will prompt you to name your project and choose some initial configuration options. Once completed, it will generate a new Next.js project in a directory named `my-next-app`. - -#### Project Structure Overview - -A typical Next.js project has the following structure: - -``` -my-next-app/ -├── node_modules/ -├── public/ -│ ├── favicon.ico -│ └── vercel.svg -├── src/ -│ ├── pages/ -│ │ ├── api/ -│ │ │ └── hello.js -│ │ ├── _app.js -│ │ ├── _document.js -│ │ └── index.js -│ ├── styles/ -│ │ ├── globals.css -│ │ └── Home.module.css -│ └── components/ -│ └── [Your components here] -├── .gitignore -├── package.json -├── README.md -└── next.config.js -``` - -:::note -**Key Directories and Files**: -- **`public/`**: Contains static assets like images, fonts, and other files that you want to serve directly. Files in this directory are accessible from the root URL. -- **`src/pages/`**: Each file in this directory automatically becomes a route. For example, `pages/index.js` maps to `/`, and `pages/about.js` maps to `/about`. - - **`_app.js`**: Customizes the default App component used by Next.js to initialize pages. - - **`_document.js`**: Customizes the default Document component, useful for augmenting the application's HTML and body tags. - - **`api/`**: Contains serverless functions that map to `/api/*` routes. -- **`src/styles/`**: Contains CSS files to style your application. -- **`src/components/`**: Contains React components used across your application. -- **`next.config.js`**: Customizes the Next.js configuration. -- **`package.json`**: Lists dependencies and scripts for your project. -::: \ No newline at end of file diff --git a/courses/Next.Js/beginner-level/Styling/Libraries.md b/courses/Next.Js/beginner-level/Styling/Libraries.md deleted file mode 100644 index 2e00f4ffb..000000000 --- a/courses/Next.Js/beginner-level/Styling/Libraries.md +++ /dev/null @@ -1,80 +0,0 @@ ---- -id: lesson-2 -title: "Integrating with CSS-in-JS Libraries" -sidebar_label: CSS with Libraries -sidebar_position: 2 -description: "Integrating with CSS-in-JS Libraries" -tags: [courses,beginner-level,FramWorks,Introduction] ---- - - -Next.js supports popular CSS-in-JS libraries like styled-components and emotion. - -**Using styled-components**: - -1. **Install styled-components and babel-plugin-styled-components**: - ```bash - npm install styled-components - npm install --save-dev babel-plugin-styled-components - ``` - -2. **Create a `.babelrc` File**: - ```json - { - "presets": ["next/babel"], - "plugins": [["styled-components", { "ssr": true }]] - } - ``` - -3. **Use styled-components in a Component**: - ```javascript - // src/pages/index.js - import styled from 'styled-components'; - - const Title = styled.h1` - color: #0070f3; - font-size: 4rem; - `; - - export default function Home() { - return ( -
- Welcome to Next.js! -
- ); - } - ``` - -**Using emotion**: - -1. **Install emotion**: - ```bash - npm install @emotion/react @emotion/styled - ``` - -2. **Use emotion in a Component**: - ```javascript - // src/pages/index.js - /** @jsxImportSource @emotion/react */ - import { css } from '@emotion/react'; - import styled from '@emotion/styled'; - - const titleStyle = css` - color: #0070f3; - font-size: 4rem; - `; - - const Title = styled.h1` - color: #0070f3; - font-size: 4rem; - `; - - export default function Home() { - return ( -
-

Welcome to Next.js with emotion!

- Styled with emotion! -
- ); - } - ``` \ No newline at end of file diff --git a/courses/Next.Js/beginner-level/Styling/_category_.json b/courses/Next.Js/beginner-level/Styling/_category_.json deleted file mode 100644 index ee33dce5e..000000000 --- a/courses/Next.Js/beginner-level/Styling/_category_.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "label": "Styling in Next.js", - "position": 5, - "link": { - "type": "generated-index", - "description": "Styling in Next.js." - } - } \ No newline at end of file diff --git a/courses/Next.Js/beginner-level/Styling/css-styling.md b/courses/Next.Js/beginner-level/Styling/css-styling.md deleted file mode 100644 index b60e33ad3..000000000 --- a/courses/Next.Js/beginner-level/Styling/css-styling.md +++ /dev/null @@ -1,104 +0,0 @@ ---- -id: lesson-1 -title: "Styling in Next.js" -sidebar_label: Styling -sidebar_position: 1 -description: "Styling in Next.js" -tags: [courses,beginner-level,FramWorks,Introduction] ---- - -Next.js offers several ways to style your applications, including using plain CSS, CSS Modules, Styled JSX, and integrating with popular CSS-in-JS libraries like styled-components and emotion. - -#### Using CSS in Next.js - -You can use global CSS files in your Next.js application by importing them in your `src/pages/_app.js` file. - -1. **Create a Global CSS File**: - - Create a CSS file in the `src/styles` directory, e.g., `globals.css`: - ```css - /* src/styles/globals.css */ - body { - margin: 0; - font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', - 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', - sans-serif; - -webkit-font-smoothing: antialiased; - -moz-osx-font-smoothing: grayscale; - } - - code { - font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New', monospace; - } - ``` - -2. **Import the Global CSS File**: - - Import the CSS file in `src/pages/_app.js`: - ```javascript - // src/pages/_app.js - import '../styles/globals.css'; - - function MyApp({ Component, pageProps }) { - return ; - } - - export default MyApp; - ``` - -#### CSS Modules - -CSS Modules provide a way to scope CSS to a specific component, avoiding global namespace collisions. - -1. **Create a CSS Module File**: - - Create a CSS Module file, e.g., `Home.module.css`: - ```css - /* src/styles/Home.module.css */ - .container { - display: flex; - flex-direction: column; - align-items: center; - justify-content: center; - height: 100vh; - } - - .title { - font-size: 4rem; - color: #0070f3; - } - ``` - -2. **Import and Use the CSS Module in a Component**: - - Import and apply the styles in your component: - ```javascript - // src/pages/index.js - import styles from '../styles/Home.module.css'; - - export default function Home() { - return ( -
-

Welcome to Next.js!

-
- ); - } - ``` - -#### Styled JSX - -Styled JSX is built into Next.js and allows you to write scoped CSS directly within your components. - -1. **Use Styled JSX in a Component**: - ```javascript - // src/pages/index.js - export default function Home() { - return ( -
-

Welcome to Next.js!

- -
- ); - } - ``` \ No newline at end of file diff --git a/courses/Next.Js/beginner-level/_category_.json b/courses/Next.Js/beginner-level/_category_.json deleted file mode 100644 index 38cbcaefb..000000000 --- a/courses/Next.Js/beginner-level/_category_.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "label": "Begginer Level", - "position": 1, - "link": { - "type": "generated-index", - "description": "Learn Next.Js Begginer Techniques." - } - } \ No newline at end of file diff --git a/courses/Next.Js/beginner-level/static-and-serverSide/_category_.json b/courses/Next.Js/beginner-level/static-and-serverSide/_category_.json deleted file mode 100644 index 24a4337b2..000000000 --- a/courses/Next.Js/beginner-level/static-and-serverSide/_category_.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "label": "Static and Server-Side Rendering", - "position": 4, - "link": { - "type": "generated-index", - "description": "Learn Next.Js Static and Server-Side Rendering." - } - } \ No newline at end of file diff --git a/courses/Next.Js/beginner-level/static-and-serverSide/concept.md b/courses/Next.Js/beginner-level/static-and-serverSide/concept.md deleted file mode 100644 index 5483dc2f4..000000000 --- a/courses/Next.Js/beginner-level/static-and-serverSide/concept.md +++ /dev/null @@ -1,160 +0,0 @@ ---- -id: lesson-2 -title: "Concepts of static and server-side rendering" -sidebar_label: Concepts -sidebar_position: 2 -description: "Concepts of static and server-side rendering" -tags: [courses, beginner-level, FramWorks, Introduction] ---- - -#### Implementing Static Generation (`getStaticProps`) - -`getStaticProps` is a Next.js function that allows you to fetch data at build time to pre-render a page. - -1. **Creating a Page with `getStaticProps`**: - - ```javascript - // src/pages/posts/[id].js - import { useRouter } from "next/router"; - - export async function getStaticProps({ params }) { - // Fetch data for the post using the id from params - const res = await fetch( - `https://jsonplaceholder.typicode.com/posts/${params.id}`, - ); - const post = await res.json(); - - return { - props: { - post, - }, - }; - } - - export async function getStaticPaths() { - // Specify dynamic routes to pre-render based on data - const res = await fetch("https://jsonplaceholder.typicode.com/posts"); - const posts = await res.json(); - - const paths = posts.map((post) => ({ - params: { id: post.id.toString() }, - })); - - return { - paths, - fallback: false, - }; - } - - export default function Post({ post }) { - const router = useRouter(); - if (router.isFallback) { - return
Loading...
; - } - - return ( -
-

{post.title}

-

{post.body}

-
- ); - } - ``` - -2. **Explanation**: - - `getStaticProps` fetches data at build time and passes it as props to the page component. - - `getStaticPaths` specifies the dynamic routes to be pre-rendered. - - `fallback: false` ensures that only the specified paths are generated at build time. - -#### Implementing Server-Side Rendering (`getServerSideProps`) - -`getServerSideProps` is a Next.js function that allows you to fetch data on each request to pre-render a page. - -1. **Creating a Page with `getServerSideProps`**: - - ```javascript - // src/pages/profile.js - export async function getServerSideProps(context) { - // Fetch data on each request - const res = await fetch("https://jsonplaceholder.typicode.com/users/1"); - const profile = await res.json(); - - return { - props: { - profile, - }, - }; - } - - export default function Profile({ profile }) { - return ( -
-

{profile.name}

-

{profile.email}

-
- ); - } - ``` - -2. **Explanation**: - - `getServerSideProps` fetches data on each request and passes it as props to the page component. - - This method ensures that the page is always up-to-date with the latest data. - -#### Incremental Static Regeneration (ISR) - -ISR allows you to update static pages after they have been built, without requiring a full rebuild of the site. - -1. **Implementing ISR with `revalidate`**: - - ```javascript - // src/pages/posts/[id].js - export async function getStaticProps({ params }) { - const res = await fetch( - `https://jsonplaceholder.typicode.com/posts/${params.id}`, - ); - const post = await res.json(); - - return { - props: { - post, - }, - revalidate: 10, // Revalidate the page every 10 seconds - }; - } - - export async function getStaticPaths() { - const res = await fetch("https://jsonplaceholder.typicode.com/posts"); - const posts = await res.json(); - - const paths = posts.map((post) => ({ - params: { id: post.id.toString() }, - })); - - return { - paths, - fallback: true, - }; - } - - export default function Post({ post }) { - const router = useRouter(); - if (router.isFallback) { - return
Loading...
; - } - - return ( -
-

{post.title}

-

{post.body}

-
- ); - } - ``` - -2. **Explanation**: - - `revalidate`: Specifies the number of seconds after which the page should be regenerated. - - With ISR, the page will be updated in the background after the specified time, providing fresh content without a full rebuild. - -#### Conclusion - -Next.js provides various methods for rendering pages, including static generation, server-side rendering, and incremental static regeneration. These features allow you to optimize performance and user experience by fetching data at build time or on each request. diff --git a/courses/Next.Js/beginner-level/static-and-serverSide/introduction.md b/courses/Next.Js/beginner-level/static-and-serverSide/introduction.md deleted file mode 100644 index 95b07c2e8..000000000 --- a/courses/Next.Js/beginner-level/static-and-serverSide/introduction.md +++ /dev/null @@ -1,123 +0,0 @@ ---- -id: lesson-1 -title: "Static and Server-Side Rendering in Next.js" -sidebar_label: Static and Server-Side Rendering -sidebar_position: 1 -description: "Static and Server-Side Rendering in Next.js" -tags: [courses, beginner-level, FramWorks, Introduction] ---- - -## Difference Between Static and Server-Side Rendering - -**Static Rendering (Static Site Generation - SSG)**: - -- **Pre-rendering**: Pages are generated at build time, and the HTML is created once and reused for each request. -- **Performance**: Faster since the content is pre-rendered and served as static files. -- **Use Cases**: Ideal for pages that do not require frequent updates, such as blogs, documentation, and marketing pages. - -**Server-Side Rendering (SSR)**: - -- **On-Demand Rendering**: Pages are generated on each request, fetching data and rendering HTML dynamically. -- **Performance**: Slower compared to static rendering because the server must generate the HTML for each request. -- **Use Cases**: Suitable for pages that require real-time data or frequent updates, such as dashboards, user profiles, and dynamic content. - -## Implementing Static Generation (`getStaticProps`) - -`getStaticProps` is a Next.js function that allows you to fetch data at build time to pre-render a page. - -1. **Creating a Page with `getStaticProps`**: - - ```javascript title="pages/posts/[id].js" - import { useRouter } from "next/router"; - - export async function getStaticProps({ params }) { - // Fetch data for the post using the id from params - const res = await fetch( - `https://jsonplaceholder.typicode.com/posts/${params.id}`, - ); - const post = await res.json(); - - return { - props: { - post, - }, - }; - } - - export async function getStaticPaths() { - // Specify dynamic routes to pre-render based on data - const res = await fetch("https://jsonplaceholder.typicode.com/posts"); - const posts = await res.json(); - - const paths = posts.map((post) => ({ - params: { id: post.id.toString() }, - })); - - return { - paths, - fallback: false, - }; - } - - export default function Post({ post }) { - const router = useRouter(); - if (router.isFallback) { - return
Loading...
; - } - - return ( -
-

{post.title}

-

{post.body}

-
- ); - } - ``` - -2. **Explanation**: - - - `getStaticProps` fetches data at build time and passes it as props to the page component. - - `getStaticPaths` specifies the dynamic routes to be pre-rendered. - - `fallback: false` ensures that only the specified paths are generated at build time. - - `router.isFallback` checks if the page is in fallback mode and displays a loading indicator. - - The `Post` component displays the post title and body fetched from the API. - -## Implementing Server-Side Rendering (`getServerSideProps`) - -`getServerSideProps` is a Next.js function that allows you to fetch data on each request to pre-render a page. - -1. **Creating a Page with `getServerSideProps`**: - - ```javascript title="pages/user/[id].js" - import { useRouter } from "next/router"; - - export async function getServerSideProps({ params }) { - // Fetch user data using the id from params - const res = await fetch( - `https://jsonplaceholder.typicode.com/users/${params.id}`, - ); - const user = await res.json(); - - return { - props: { - user, - }, - }; - } - - export default function User({ user }) { - return ( -
-

{user.name}

-

Email: {user.email}

-
- ); - } - ``` - -2. **Explanation**: - - - `getServerSideProps` fetches data on each request and passes it as props to the page component. - - The `User` component displays the user's name and email fetched from the API. - -In this lesson, you learned about static and server-side rendering in Next.js and how to implement them using `getStaticProps` and `getServerSideProps` functions. Static rendering is ideal for content that does not change frequently, while server-side rendering is suitable for real-time data and dynamic content. From 809db018794336f2197f48400a1c2bda8a3ec8e3 Mon Sep 17 00:00:00 2001 From: Sivaprasath <121082414+sivaprasath2004@users.noreply.github.com> Date: Sat, 20 Jul 2024 21:53:05 +0530 Subject: [PATCH 2/5] Add files via upload --- .../Authentication/Implement-Auth.md | 77 ++++++ .../Intermediate-level/Authentication/JWT.md | 53 ++++ .../Authentication/Role-based.md | 61 +++++ .../Authentication/_category_.json | 8 + .../Authentication/protection-Routes.md | 73 ++++++ .../Data-Fetching/GraphQl.md | 69 ++++++ .../Data-Fetching/Handling.md | 73 ++++++ .../Intermediate-level/Data-Fetching/SWR.md | 48 ++++ .../Data-Fetching/_category_.json | 8 + .../Data-Fetching/fetching-Data.md | 119 +++++++++ .../Internationalization/Handling-dynamic.md | 60 +++++ .../Internationalization/Introduction.md | 72 ++++++ .../Loading-and-Managing.md | 79 ++++++ .../Internationalization/_category_.json | 8 + .../Middleware/Introduction.md | 86 +++++++ .../Middleware/Middleware-concept.md | 55 +++++ .../Middleware/_category_.json | 8 + .../Middleware/routing-tech.md | 42 ++++ .../Intermediate-level/_category_.json | 8 + courses/Next.Js/Overview.md | 80 +++++++ courses/Next.Js/_category_.json | 8 + .../Advance-Routing/Customizing.md | 136 +++++++++++ .../Advance-Routing/Dynamic-Route.md | 80 +++++++ .../Advance-Routing/_category_.json | 8 + .../Advance-data-fetching/_category_.json | 8 + .../dynamic-generation.md | 191 +++++++++++++++ .../static-generation.md | 100 ++++++++ .../Advance-server-side-render/SSR.md | 160 +++++++++++++ .../_category_.json | 8 + .../Advance-server-side-render/customize.md | 142 +++++++++++ .../advance-level/GraphQL/Introduction.md | 106 ++++++++ .../advance-level/GraphQL/_category_.json | 8 + .../advance-level/GraphQL/apollo-client.md | 226 ++++++++++++++++++ courses/Next.Js/advance-level/_category_.json | 8 + .../beginner-level/Introduction/Frameworks.md | 22 ++ .../Introduction/_category_.json | 8 + .../Introduction/introduction.md | 31 +++ .../beginner-level/Introduction/settingUp.md | 39 +++ .../Pages-and-routing/FIlebase-Routing.md | 91 +++++++ .../Pages-and-routing/_category_.json | 8 + .../Pages-and-routing/creating-pages.md | 45 ++++ .../Next.Js/beginner-level/Routes/Database.md | 140 +++++++++++ .../beginner-level/Routes/Introduction.md | 48 ++++ .../beginner-level/Routes/_category_.json | 8 + .../Started/Running-development.md | 66 +++++ .../beginner-level/Started/_category_.json | 8 + .../Started/creating-project.md | 67 ++++++ .../beginner-level/Styling/Libraries.md | 80 +++++++ .../beginner-level/Styling/_category_.json | 8 + .../beginner-level/Styling/css-styling.md | 104 ++++++++ .../Next.Js/beginner-level/_category_.json | 8 + .../static-and-serverSide/_category_.json | 8 + .../static-and-serverSide/concept.md | 170 +++++++++++++ .../static-and-serverSide/introduction.md | 21 ++ 54 files changed, 3256 insertions(+) create mode 100644 courses/Next.Js/Intermediate-level/Authentication/Implement-Auth.md create mode 100644 courses/Next.Js/Intermediate-level/Authentication/JWT.md create mode 100644 courses/Next.Js/Intermediate-level/Authentication/Role-based.md create mode 100644 courses/Next.Js/Intermediate-level/Authentication/_category_.json create mode 100644 courses/Next.Js/Intermediate-level/Authentication/protection-Routes.md create mode 100644 courses/Next.Js/Intermediate-level/Data-Fetching/GraphQl.md create mode 100644 courses/Next.Js/Intermediate-level/Data-Fetching/Handling.md create mode 100644 courses/Next.Js/Intermediate-level/Data-Fetching/SWR.md create mode 100644 courses/Next.Js/Intermediate-level/Data-Fetching/_category_.json create mode 100644 courses/Next.Js/Intermediate-level/Data-Fetching/fetching-Data.md create mode 100644 courses/Next.Js/Intermediate-level/Internationalization/Handling-dynamic.md create mode 100644 courses/Next.Js/Intermediate-level/Internationalization/Introduction.md create mode 100644 courses/Next.Js/Intermediate-level/Internationalization/Loading-and-Managing.md create mode 100644 courses/Next.Js/Intermediate-level/Internationalization/_category_.json create mode 100644 courses/Next.Js/Intermediate-level/Middleware/Introduction.md create mode 100644 courses/Next.Js/Intermediate-level/Middleware/Middleware-concept.md create mode 100644 courses/Next.Js/Intermediate-level/Middleware/_category_.json create mode 100644 courses/Next.Js/Intermediate-level/Middleware/routing-tech.md create mode 100644 courses/Next.Js/Intermediate-level/_category_.json create mode 100644 courses/Next.Js/Overview.md create mode 100644 courses/Next.Js/_category_.json create mode 100644 courses/Next.Js/advance-level/Advance-Routing/Customizing.md create mode 100644 courses/Next.Js/advance-level/Advance-Routing/Dynamic-Route.md create mode 100644 courses/Next.Js/advance-level/Advance-Routing/_category_.json create mode 100644 courses/Next.Js/advance-level/Advance-data-fetching/_category_.json create mode 100644 courses/Next.Js/advance-level/Advance-data-fetching/dynamic-generation.md create mode 100644 courses/Next.Js/advance-level/Advance-data-fetching/static-generation.md create mode 100644 courses/Next.Js/advance-level/Advance-server-side-render/SSR.md create mode 100644 courses/Next.Js/advance-level/Advance-server-side-render/_category_.json create mode 100644 courses/Next.Js/advance-level/Advance-server-side-render/customize.md create mode 100644 courses/Next.Js/advance-level/GraphQL/Introduction.md create mode 100644 courses/Next.Js/advance-level/GraphQL/_category_.json create mode 100644 courses/Next.Js/advance-level/GraphQL/apollo-client.md create mode 100644 courses/Next.Js/advance-level/_category_.json create mode 100644 courses/Next.Js/beginner-level/Introduction/Frameworks.md create mode 100644 courses/Next.Js/beginner-level/Introduction/_category_.json create mode 100644 courses/Next.Js/beginner-level/Introduction/introduction.md create mode 100644 courses/Next.Js/beginner-level/Introduction/settingUp.md create mode 100644 courses/Next.Js/beginner-level/Pages-and-routing/FIlebase-Routing.md create mode 100644 courses/Next.Js/beginner-level/Pages-and-routing/_category_.json create mode 100644 courses/Next.Js/beginner-level/Pages-and-routing/creating-pages.md create mode 100644 courses/Next.Js/beginner-level/Routes/Database.md create mode 100644 courses/Next.Js/beginner-level/Routes/Introduction.md create mode 100644 courses/Next.Js/beginner-level/Routes/_category_.json create mode 100644 courses/Next.Js/beginner-level/Started/Running-development.md create mode 100644 courses/Next.Js/beginner-level/Started/_category_.json create mode 100644 courses/Next.Js/beginner-level/Started/creating-project.md create mode 100644 courses/Next.Js/beginner-level/Styling/Libraries.md create mode 100644 courses/Next.Js/beginner-level/Styling/_category_.json create mode 100644 courses/Next.Js/beginner-level/Styling/css-styling.md create mode 100644 courses/Next.Js/beginner-level/_category_.json create mode 100644 courses/Next.Js/beginner-level/static-and-serverSide/_category_.json create mode 100644 courses/Next.Js/beginner-level/static-and-serverSide/concept.md create mode 100644 courses/Next.Js/beginner-level/static-and-serverSide/introduction.md diff --git a/courses/Next.Js/Intermediate-level/Authentication/Implement-Auth.md b/courses/Next.Js/Intermediate-level/Authentication/Implement-Auth.md new file mode 100644 index 000000000..53658058b --- /dev/null +++ b/courses/Next.Js/Intermediate-level/Authentication/Implement-Auth.md @@ -0,0 +1,77 @@ +--- +id: lesson-1 +title: "Authentication and Authorization in Next.js" +sidebar_label: Authentication and Authorization +sidebar_position: 1 +description: "Authentication and Authorization in Next.js" +tags: [courses,intermediate-level,FramWorks,Introduction] +--- + + +Implementing authentication and authorization in Next.js can be streamlined using libraries like NextAuth.js for handling various authentication strategies, JWT-based authentication for token management, and role-based access control to protect routes and API endpoints. + +#### Implementing Authentication with NextAuth.js + +NextAuth.js is a flexible authentication library for Next.js applications. It supports various authentication providers like Google, GitHub, and custom email/password. + +1. **Install NextAuth.js**: + ```bash + npm install next-auth + ``` + +2. **Configure NextAuth.js**: + - Create a new API route for NextAuth in `src/pages/api/auth/[...nextauth].js`: + ```javascript + // src/pages/api/auth/[...nextauth].js + import NextAuth from 'next-auth'; + import Providers from 'next-auth/providers'; + + export default NextAuth({ + providers: [ + Providers.Google({ + clientId: process.env.GOOGLE_CLIENT_ID, + clientSecret: process.env.GOOGLE_CLIENT_SECRET, + }), + // Add other providers here + ], + database: process.env.DATABASE_URL, // Optional: For storing user accounts in a database + }); + ``` + +3. **Add Environment Variables**: + - Create a `.env.local` file in the root of your project and add the required environment variables: + ```env + GOOGLE_CLIENT_ID=your-google-client-id + GOOGLE_CLIENT_SECRET=your-google-client-secret + DATABASE_URL=your-database-url + ``` + +4. **Add Authentication to Pages**: + - Use the `useSession` hook to access the authentication session: + ```javascript + // src/pages/index.js + import { useSession, signIn, signOut } from 'next-auth/client'; + + export default function Home() { + const [session, loading] = useSession(); + + return ( +
+

NextAuth.js Authentication

+ {loading &&

Loading...

} + {!session && ( +
+

You are not signed in.

+ +
+ )} + {session && ( +
+

Signed in as {session.user.email}

+ +
+ )} +
+ ); + } + ``` \ No newline at end of file diff --git a/courses/Next.Js/Intermediate-level/Authentication/JWT.md b/courses/Next.Js/Intermediate-level/Authentication/JWT.md new file mode 100644 index 000000000..cd2d48999 --- /dev/null +++ b/courses/Next.Js/Intermediate-level/Authentication/JWT.md @@ -0,0 +1,53 @@ +--- +id: lesson-2 +title: "JWT-Based Authentication" +sidebar_label: JWT-Based Authentication +sidebar_position: 2 +description: "JWT-Based Authentication" +tags: [courses,intermediate-level,FramWorks,Introduction] +--- + + +JWT (JSON Web Token) is a common method for securing APIs by encoding user information within a token. + +1. **Install JWT Dependencies**: + ```bash + npm install jsonwebtoken + ``` + +2. **Generate JWTs**: + ```javascript + // src/utils/jwt.js + import jwt from 'jsonwebtoken'; + + const secret = process.env.JWT_SECRET; + + export function generateToken(user) { + return jwt.sign({ id: user.id, email: user.email }, secret, { expiresIn: '1h' }); + } + + export function verifyToken(token) { + try { + return jwt.verify(token, secret); + } catch (err) { + return null; + } + } + ``` + +3. **Protecting API Routes**: + ```javascript + // src/pages/api/protected.js + import { verifyToken } from '../../utils/jwt'; + + export default function handler(req, res) { + const token = req.headers.authorization?.split(' ')[1]; + const user = verifyToken(token); + + if (!user) { + return res.status(401).json({ message: 'Unauthorized' }); + } + + res.status(200).json({ message: 'This is a protected route', user }); + } + ``` \ No newline at end of file diff --git a/courses/Next.Js/Intermediate-level/Authentication/Role-based.md b/courses/Next.Js/Intermediate-level/Authentication/Role-based.md new file mode 100644 index 000000000..69a4ad9a9 --- /dev/null +++ b/courses/Next.Js/Intermediate-level/Authentication/Role-based.md @@ -0,0 +1,61 @@ +--- +id: lesson-3 +title: "Role-Based Access Control" +sidebar_label: Protecting Routes and API Endpoints +sidebar_position: 3 +description: "Role-Based Access Control" +tags: [courses,intermediate-level,FramWorks,Introduction] +--- + + + +1. **Assign Roles to Users**: + - Modify your user model to include roles: + ```javascript + // src/models/User.js + import mongoose from 'mongoose'; + + const UserSchema = new mongoose.Schema({ + name: String, + email: String, + role: { + type: String, + enum: ['user', 'admin'], + default: 'user', + }, + }); + + export default mongoose.models.User || mongoose.model('User', UserSchema); + ``` + +2. **Create Middleware for Role-Based Access Control**: + ```javascript + // src/utils/withRole.js + import { verifyToken } from './jwt'; + + export function withRole(handler, role) { + return async (req, res) => { + const token = req.headers.authorization?.split(' ')[1]; + const user = verifyToken(token); + + if (!user || user.role !== role) { + return res.status(403).json({ message: 'Forbidden' }); + } + + req.user = user; + return handler(req, res); + }; + } + ``` + +3. **Protect Routes with Role-Based Access Control**: + ```javascript + // src/pages/api/admin.js + import { withRole } from '../../utils/withRole'; + + const handler = (req, res) => { + res.status(200).json({ message: 'Admin route', user: req.user }); + }; + + export default withRole(handler, 'admin'); + ``` diff --git a/courses/Next.Js/Intermediate-level/Authentication/_category_.json b/courses/Next.Js/Intermediate-level/Authentication/_category_.json new file mode 100644 index 000000000..005cbdc85 --- /dev/null +++ b/courses/Next.Js/Intermediate-level/Authentication/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Authentication and Authorization", + "position": 2, + "link": { + "type": "generated-index", + "description": "Learn Next.Js Authentication and Authorization." + } + } \ No newline at end of file diff --git a/courses/Next.Js/Intermediate-level/Authentication/protection-Routes.md b/courses/Next.Js/Intermediate-level/Authentication/protection-Routes.md new file mode 100644 index 000000000..ce7bd3cdb --- /dev/null +++ b/courses/Next.Js/Intermediate-level/Authentication/protection-Routes.md @@ -0,0 +1,73 @@ +--- +id: lesson-4 +title: "Protecting Routes and API Endpoints" +sidebar_label: Protecting Routes and API Endpoints +sidebar_position: 4 +description: "Protecting Routes and API Endpoints" +tags: [courses,intermediate-level,FramWorks,Introduction] +--- + + +1. **Protecting Next.js Pages**: + - Use the `getServerSideProps` function to protect pages: + ```javascript + // src/pages/protected.js + import { getSession } from 'next-auth/client'; + + export default function ProtectedPage({ session }) { + if (!session) { + return

Access Denied

; + } + + return

Welcome, {session.user.email}

; + } + + export async function getServerSideProps(context) { + const session = await getSession(context); + + if (!session) { + return { + redirect: { + destination: '/api/auth/signin', + permanent: false, + }, + }; + } + + return { + props: { session }, + }; + } + ``` + +2. **Protecting API Endpoints with Middleware**: + ```javascript + // src/utils/withAuth.js + import { verifyToken } from './jwt'; + + export function withAuth(handler) { + return async (req, res) => { + const token = req.headers.authorization?.split(' ')[1]; + const user = verifyToken(token); + + if (!user) { + return res.status(401).json({ message: 'Unauthorized' }); + } + + req.user = user; + return handler(req, res); + }; + } + ``` + + ```javascript + // src/pages/api/protected.js + import { withAuth } from '../../utils/withAuth'; + + const handler = (req, res) => { + res.status(200).json({ message: 'Protected route', user: req.user }); + }; + + export default withAuth(handler); + ``` + \ No newline at end of file diff --git a/courses/Next.Js/Intermediate-level/Data-Fetching/GraphQl.md b/courses/Next.Js/Intermediate-level/Data-Fetching/GraphQl.md new file mode 100644 index 000000000..d32a1a349 --- /dev/null +++ b/courses/Next.Js/Intermediate-level/Data-Fetching/GraphQl.md @@ -0,0 +1,69 @@ +--- +id: lesson-3 +title: "Using GraphQL with Next.js" +sidebar_label: Data Fetching and Caching +sidebar_position: 3 +description: "Using GraphQL with Next.js" +tags: [courses,intermediate-level,FramWorks,Introduction] +--- + + +You can use GraphQL with Next.js using Apollo Client or other GraphQL clients. + +1. **Install Apollo Client**: + ```bash + npm install @apollo/client graphql + ``` + +2. **Setup Apollo Client**: + ```javascript + // src/lib/apolloClient.js + import { ApolloClient, InMemoryCache } from '@apollo/client'; + + const client = new ApolloClient({ + uri: 'https://your-graphql-endpoint', + cache: new InMemoryCache(), + }); + + export default client; + ``` + +3. **Use Apollo Client in a Page**: + ```javascript + // src/pages/index.js + import { ApolloProvider, gql, useQuery } from '@apollo/client'; + import client from '../lib/apolloClient'; + + const GET_POSTS = gql` + query GetPosts { + posts { + id + title + } + } + `; + + function Posts() { + const { loading, error, data } = useQuery(GET_POSTS); + + if (loading) return

Loading...

; + if (error) return

Error :(

; + + return ( + + ); + } + + export default function Home() { + return ( + +

Posts

+ +
+ ); + } + ``` diff --git a/courses/Next.Js/Intermediate-level/Data-Fetching/Handling.md b/courses/Next.Js/Intermediate-level/Data-Fetching/Handling.md new file mode 100644 index 000000000..9f7d685ac --- /dev/null +++ b/courses/Next.Js/Intermediate-level/Data-Fetching/Handling.md @@ -0,0 +1,73 @@ +--- +id: lesson-4 +title: "Handling Data Fetching Errors" +sidebar_label: Handling Fetching Errors +sidebar_position: 4 +description: "Handling Data Fetching Errors" +tags: [courses,intermediate-level,FramWorks,Introduction] +--- + + +Handling errors in data fetching is crucial to provide a good user experience. + +1. **Error Handling with `getStaticProps` and `getServerSideProps`**: + ```javascript + export async function getStaticProps() { + try { + const res = await fetch('https://jsonplaceholder.typicode.com/posts'); + const posts = await res.json(); + return { props: { posts } }; + } catch (error) { + return { props: { error: 'Failed to fetch data' } }; + } + } + + export default function Home({ posts, error }) { + if (error) { + return
{error}
; + } + + return ( +
+

Posts

+ +
+ ); + } + ``` + +2. **Error Handling with SWR**: + ```javascript + import useSWR from 'swr'; + + const fetcher = url => fetch(url).then(res => res.json()); + + export default function Home() { + const { data: posts, error } = useSWR('https://jsonplaceholder.typicode.com/posts', fetcher); + + if (error) return
Failed to load: {error.message}
; + if (!posts) return
Loading...
; + + return ( +
+

Posts

+ +
+ ); + } + ``` + + **Output:** + +
+ Failed to load: 404 server not found +
+
\ No newline at end of file diff --git a/courses/Next.Js/Intermediate-level/Data-Fetching/SWR.md b/courses/Next.Js/Intermediate-level/Data-Fetching/SWR.md new file mode 100644 index 000000000..e1daeacb4 --- /dev/null +++ b/courses/Next.Js/Intermediate-level/Data-Fetching/SWR.md @@ -0,0 +1,48 @@ +--- +id: lesson-2 +title: "SWR (Stale-While-Revalidate) for Data Fetching and Caching" +sidebar_label: SWR (Stale-While-Revalidate) +sidebar_position: 2 +description: "SWR (Stale-While-Revalidate) for Data Fetching and Caching" +tags: [courses,intermediate-level,FramWorks,Introduction] +--- + + + +SWR is a React Hooks library for data fetching, providing features like caching, revalidation, focus tracking, and more. + +1. **Install SWR**: + ```bash + npm install swr + ``` + +2. **Using SWR**: + ```javascript + // src/pages/index.js + import useSWR from 'swr'; + + const fetcher = url => fetch(url).then(res => res.json()); + + export default function Home() { + const { data: posts, error } = useSWR('https://jsonplaceholder.typicode.com/posts', fetcher); + + if (error) return
Failed to load
; + if (!posts) return
Loading...
; + + return ( +
+

Posts

+ +
+ ); + } + ``` + +**Key Features of SWR**: +- **Stale-While-Revalidate**: Data is returned from the cache first (stale), then fetches the latest data in the background (revalidate). +- **Automatic Revalidation**: Data is revalidated on focus, network reconnect, and interval-based revalidation. +- **Error Handling**: Provides built-in error handling and state management. diff --git a/courses/Next.Js/Intermediate-level/Data-Fetching/_category_.json b/courses/Next.Js/Intermediate-level/Data-Fetching/_category_.json new file mode 100644 index 000000000..23e48253e --- /dev/null +++ b/courses/Next.Js/Intermediate-level/Data-Fetching/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Data Fetching", + "position": 1, + "link": { + "type": "generated-index", + "description": "Learn Next.Js Data Fetching." + } + } \ No newline at end of file diff --git a/courses/Next.Js/Intermediate-level/Data-Fetching/fetching-Data.md b/courses/Next.Js/Intermediate-level/Data-Fetching/fetching-Data.md new file mode 100644 index 000000000..a76fc371d --- /dev/null +++ b/courses/Next.Js/Intermediate-level/Data-Fetching/fetching-Data.md @@ -0,0 +1,119 @@ +--- +id: lesson-1 +title: "Data Fetching and Caching in Next.js" +sidebar_label: Data Fetching and Caching +sidebar_position: 1 +description: "Data Fetching and Caching in Next.js" +tags: [courses,intermediate-level,FramWorks,Introduction] +--- + + +Efficient data fetching and caching are crucial for building performant and responsive web applications. Next.js provides several methods for fetching data, including the use of the SWR (Stale-While-Revalidate) library for caching. Additionally, Next.js supports fetching data from GraphQL APIs. + +#### Fetching Data from APIs + +Next.js allows you to fetch data in different ways depending on your requirements. The primary methods are: + +1. **`getStaticProps`**: Fetch data at build time for static generation. +2. **`getServerSideProps`**: Fetch data on each request for server-side rendering. +3. **Client-Side Fetching**: Fetch data on the client side, typically using `useEffect`. + +**Example with `getStaticProps`**: +```javascript +// src/pages/index.js +export async function getStaticProps() { + const res = await fetch('https://jsonplaceholder.typicode.com/posts'); + const posts = await res.json(); + + return { + props: { + posts, + }, + }; +} + +export default function Home({ posts }) { + return ( +
+

Posts

+ +
+ ); +} +``` + +**Example with `getServerSideProps`**: +```javascript +// src/pages/index.js +export async function getServerSideProps() { + const res = await fetch('https://jsonplaceholder.typicode.com/posts'); + const posts = await res.json(); + + return { + props: { + posts, + }, + }; +} + +export default function Home({ posts }) { + return ( +
+

Posts

+ +
+ ); +} +``` + +**Example with Client-Side Fetching**: +```javascript +// src/pages/index.js +import { useState, useEffect } from 'react'; + +export default function Home() { + const [posts, setPosts] = useState([]); + + useEffect(() => { + async function fetchData() { + const res = await fetch('https://jsonplaceholder.typicode.com/posts'); + const posts = await res.json(); + setPosts(posts); + } + fetchData(); + }, []); + + return ( +
+

Posts

+ +
+ ); +} +``` + +**Output:** + + +

Posts

+ +
\ No newline at end of file diff --git a/courses/Next.Js/Intermediate-level/Internationalization/Handling-dynamic.md b/courses/Next.Js/Intermediate-level/Internationalization/Handling-dynamic.md new file mode 100644 index 000000000..68a0c6ab8 --- /dev/null +++ b/courses/Next.Js/Intermediate-level/Internationalization/Handling-dynamic.md @@ -0,0 +1,60 @@ +--- +id: lesson-3 +title: "Handling Dynamic Content in Different Languages" +sidebar_label: Handling Languages +sidebar_position: 3 +description: "Handling Dynamic Content in Different Languages" +tags: [courses,intermediate-level,FramWorks,Introduction] +--- + + +1. **Dynamic Routes with i18n**: + - Create dynamic route files and fetch localized content based on the locale: + ```javascript + // pages/[locale]/[slug].js + import { useRouter } from 'next/router'; + import { useTranslation } from 'next-i18next'; + + export default function Post({ post }) { + const { t } = useTranslation('common'); + + return ( +
+

{t(post.title)}

+

{t(post.content)}

+
+ ); + } + + export async function getStaticPaths() { + // Fetch or define paths for all locales + const paths = [ + { params: { locale: 'en', slug: 'hello-world' } }, + { params: { locale: 'fr', slug: 'bonjour-le-monde' } }, + { params: { locale: 'de', slug: 'hallo-welt' } }, + ]; + return { paths, fallback: false }; + } + + export async function getStaticProps({ params }) { + const { locale, slug } = params; + const post = await fetchPostData(locale, slug); + + return { + props: { + post, + ...(await serverSideTranslations(locale, ['common'])), + }, + }; + } + ``` + +2. **Fetching Localized Data**: + - Implement a function to fetch localized data: + ```javascript + async function fetchPostData(locale, slug) { + const res = await fetch(`https://api.example.com/posts?locale=${locale}&slug=${slug}`); + const data = await res.json(); + return data; + } + ``` \ No newline at end of file diff --git a/courses/Next.Js/Intermediate-level/Internationalization/Introduction.md b/courses/Next.Js/Intermediate-level/Internationalization/Introduction.md new file mode 100644 index 000000000..552e7fdab --- /dev/null +++ b/courses/Next.Js/Intermediate-level/Internationalization/Introduction.md @@ -0,0 +1,72 @@ +--- +id: lesson-1 +title: "Internationalization (i18n) in Next.js" +sidebar_label: Internationalization (i18n) +sidebar_position: 1 +description: "Internationalization (i18n) in Next.js" +tags: [courses,intermediate-level,FramWorks,Introduction] +--- + + +Internationalization (i18n) is crucial for creating applications that support multiple languages and locales. Next.js offers built-in support for internationalized routing and provides tools to load and manage translations effectively. + +#### Setting Up Internationalization in Next.js + +1. **Install Required Packages**: + - If you need a library to help with translations, such as `next-i18next`, install it: + ```bash + npm install next-i18next + ``` + +2. **Configure `next.config.js` for i18n**: + - Add i18n configuration to your `next.config.js` file: + ```javascript + // next.config.js + module.exports = { + i18n: { + locales: ['en', 'fr', 'de'], // List of supported locales + defaultLocale: 'en', // Default locale + }, + }; + ``` + +#### Using the Next.js i18n Routing Feature + +1. **Creating Locale-specific Files**: + - Create directories and files for each locale under the `pages` directory: + ``` + pages/ + ├── index.js + ├── about.js + ├── fr/ + │ ├── index.js + │ └── about.js + ├── de/ + │ ├── index.js + │ └── about.js + ``` + +2. **Linking Between Locales**: + - Use the `next/link` component to link between different locales: + ```javascript + // pages/index.js + import Link from 'next/link'; + import { useRouter } from 'next/router'; + + export default function Home() { + const { locale, locales, asPath } = useRouter(); + + return ( +
+

Hello World

+ +
+ ); + } + ``` diff --git a/courses/Next.Js/Intermediate-level/Internationalization/Loading-and-Managing.md b/courses/Next.Js/Intermediate-level/Internationalization/Loading-and-Managing.md new file mode 100644 index 000000000..b86bcc742 --- /dev/null +++ b/courses/Next.Js/Intermediate-level/Internationalization/Loading-and-Managing.md @@ -0,0 +1,79 @@ +--- +id: lesson-2 +title: "Loading and Managing Translations" +sidebar_label: Loading and Managing +sidebar_position: 2 +description: "Loading and Managing Translations" +tags: [courses,intermediate-level,FramWorks,Introduction] +--- + + +1. **Using `next-i18next`**: + - Initialize `next-i18next` in your project: + ```javascript + // i18n.js + const NextI18Next = require('next-i18next').default; + + const NextI18NextInstance = new NextI18Next({ + defaultLanguage: 'en', + otherLanguages: ['fr', 'de'], + }); + + module.exports = NextI18NextInstance; + module.exports.default = NextI18NextInstance; + ``` + +2. **Adding Translation Files**: + - Create translation files for each language under a `public/locales` directory: + ``` + public/ + └── locales/ + ├── en/ + │ └── common.json + ├── fr/ + │ └── common.json + └── de/ + └── common.json + ``` + - Example content for `common.json`: + ```json + // public/locales/en/common.json + { + "welcome": "Welcome", + "about": "About Us" + } + + // public/locales/fr/common.json + { + "welcome": "Bienvenue", + "about": "À propos de nous" + } + + // public/locales/de/common.json + { + "welcome": "Willkommen", + "about": "Über uns" + } + ``` + +3. **Using Translations in Components**: + - Use the `useTranslation` hook provided by `next-i18next` to load and use translations: + ```javascript + // pages/index.js + import { useTranslation } from 'next-i18next'; + import { serverSideTranslations } from 'next-i18next/serverSideTranslations'; + + export default function Home() { + const { t } = useTranslation('common'); + + return

{t('welcome')}

; + } + + export async function getStaticProps({ locale }) { + return { + props: { + ...(await serverSideTranslations(locale, ['common'])), + }, + }; + } + ``` \ No newline at end of file diff --git a/courses/Next.Js/Intermediate-level/Internationalization/_category_.json b/courses/Next.Js/Intermediate-level/Internationalization/_category_.json new file mode 100644 index 000000000..ce6e40b86 --- /dev/null +++ b/courses/Next.Js/Intermediate-level/Internationalization/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Internationalization (i18n)", + "position": 4, + "link": { + "type": "generated-index", + "description": "Learn Next.Js Internationalization (i18n)." + } + } \ No newline at end of file diff --git a/courses/Next.Js/Intermediate-level/Middleware/Introduction.md b/courses/Next.Js/Intermediate-level/Middleware/Introduction.md new file mode 100644 index 000000000..29449db6a --- /dev/null +++ b/courses/Next.Js/Intermediate-level/Middleware/Introduction.md @@ -0,0 +1,86 @@ +--- +id: lesson-1 +title: "Middleware and Custom Server in Next.js" +sidebar_label: Middleware and Custom Server in Next.js +sidebar_position: 1 +description: "Middleware and Custom Server in Next.js" +tags: [courses,intermediate-level,FramWorks,Introduction] +--- + + +Middleware and custom servers in Next.js can enhance functionality by adding features like logging, authentication, and advanced routing. Below, we'll explore how to implement middleware, set up a custom server using Express.js, and utilize middleware for various purposes. + +#### Understanding and Using Middleware in Next.js + +Middleware in Next.js can be added at the API route level or through a custom server setup. + +1. **API Route Middleware**: + - Middleware functions can be added directly in API routes to handle specific tasks like logging and authentication. + + **Example: Logging Middleware for an API Route**: + ```javascript + // src/pages/api/logged.js + export default function handler(req, res) { + console.log(`Request method: ${req.method}`); + res.status(200).json({ message: 'Logged request method' }); + } + ``` + +2. **Global Middleware Using Custom Server**: + - For more complex middleware usage, setting up a custom server with Express.js allows applying middleware globally. + +#### Creating a Custom Server with Express.js + +A custom server can provide more control over the request handling process. Here's how to set up a custom server with Express.js: + +1. **Install Required Packages**: + ```bash + npm install express + ``` + +2. **Set Up the Custom Server**: + - Create a `server.js` file at the root of your project: + ```javascript + // server.js + const express = require('express'); + const next = require('next'); + + const dev = process.env.NODE_ENV !== 'production'; + const app = next({ dev }); + const handle = app.getRequestHandler(); + + app.prepare().then(() => { + const server = express(); + + // Example of a custom middleware for logging + server.use((req, res, next) => { + console.log(`Request URL: ${req.url}`); + next(); + }); + + // Example route + server.get('/custom', (req, res) => { + return app.render(req, res, '/custom', req.query); + }); + + // Default Next.js request handler + server.all('*', (req, res) => { + return handle(req, res); + }); + + server.listen(3000, err => { + if (err) throw err; + console.log('> Ready on http://localhost:3000'); + }); + }); + ``` + +3. **Modify `package.json` to Use the Custom Server**: + ```json + // package.json + "scripts": { + "dev": "node server.js", + "build": "next build", + "start": "NODE_ENV=production node server.js" + } + ``` diff --git a/courses/Next.Js/Intermediate-level/Middleware/Middleware-concept.md b/courses/Next.Js/Intermediate-level/Middleware/Middleware-concept.md new file mode 100644 index 000000000..811cef2a9 --- /dev/null +++ b/courses/Next.Js/Intermediate-level/Middleware/Middleware-concept.md @@ -0,0 +1,55 @@ +--- +id: lesson-2 +title: "Using Middleware for Logging, Authentication, etc." +sidebar_label: Using Middleware for Logging, Authentication, etc. +sidebar_position: 2 +description: "Using Middleware for Logging, Authentication, etc." +tags: [courses,intermediate-level,FramWorks,Introduction] +--- + + +1. **Logging Middleware**: + ```javascript + server.use((req, res, next) => { + console.log(`Request URL: ${req.url}, Method: ${req.method}`); + next(); + }); + ``` + +2. **Authentication Middleware**: + ```javascript + const jwt = require('jsonwebtoken'); + + server.use((req, res, next) => { + const token = req.headers.authorization?.split(' ')[1]; + if (token) { + try { + req.user = jwt.verify(token, process.env.JWT_SECRET); + } catch (err) { + return res.status(401).json({ message: 'Invalid Token' }); + } + } + next(); + }); + ``` + +3. **Combining Middleware**: + - Middleware can be combined for various purposes: + ```javascript + server.use((req, res, next) => { + console.log(`Request URL: ${req.url}`); + next(); + }); + + server.use((req, res, next) => { + const token = req.headers.authorization?.split(' ')[1]; + if (token) { + try { + req.user = jwt.verify(token, process.env.JWT_SECRET); + } catch (err) { + return res.status(401).json({ message: 'Invalid Token' }); + } + } + next(); + }); + ``` diff --git a/courses/Next.Js/Intermediate-level/Middleware/_category_.json b/courses/Next.Js/Intermediate-level/Middleware/_category_.json new file mode 100644 index 000000000..df83bef03 --- /dev/null +++ b/courses/Next.Js/Intermediate-level/Middleware/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Middleware and Custom Server", + "position": 3, + "link": { + "type": "generated-index", + "description": "Learn Next.Js Middleware and Custom Server." + } + } \ No newline at end of file diff --git a/courses/Next.Js/Intermediate-level/Middleware/routing-tech.md b/courses/Next.Js/Intermediate-level/Middleware/routing-tech.md new file mode 100644 index 000000000..82d99181e --- /dev/null +++ b/courses/Next.Js/Intermediate-level/Middleware/routing-tech.md @@ -0,0 +1,42 @@ +--- +id: lesson-3 +title: "Advanced Routing Techniques with a Custom Server" +sidebar_label: Advanced Routing Technique +sidebar_position: 3 +description: "Advanced Routing Techniques with a Custom Server" +tags: [courses,intermediate-level,FramWorks,Introduction] +--- + +A custom server enables more advanced routing capabilities beyond the file-based routing system provided by Next.js. + +1. **Custom Route Handling**: + ```javascript + server.get('/custom-route', (req, res) => { + return app.render(req, res, '/custom', req.query); + }); + ``` + +2. **Dynamic Routing**: + ```javascript + server.get('/post/:id', (req, res) => { + const actualPage = '/post'; + const queryParams = { id: req.params.id }; + return app.render(req, res, actualPage, queryParams); + }); + ``` + +3. **Middleware Specific to Routes**: + ```javascript + server.use('/protected', (req, res, next) => { + const token = req.headers.authorization?.split(' ')[1]; + if (!token) { + return res.status(401).json({ message: 'Unauthorized' }); + } + next(); + }); + + server.get('/protected', (req, res) => { + return res.status(200).json({ message: 'This is a protected route' }); + }); + ``` + \ No newline at end of file diff --git a/courses/Next.Js/Intermediate-level/_category_.json b/courses/Next.Js/Intermediate-level/_category_.json new file mode 100644 index 000000000..44d8d0893 --- /dev/null +++ b/courses/Next.Js/Intermediate-level/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Intermediate Level", + "position": 2, + "link": { + "type": "generated-index", + "description": "Learn Next.Js more Topics & Techniques." + } + } \ No newline at end of file diff --git a/courses/Next.Js/Overview.md b/courses/Next.Js/Overview.md new file mode 100644 index 000000000..011196eb5 --- /dev/null +++ b/courses/Next.Js/Overview.md @@ -0,0 +1,80 @@ +--- +title: Welcome to Learning Path +sidebar_label: Course Overview +sidebar_position: 1 +description: Next.js Course Outline. +tags: [courses,Next.Js] +keywoards: [courses,Database,Next.Js] +author: [CodeHarborHub, Ajay Dhangar] +--- + + +### Beginner Level + +**1. Introduction to Next.js** + - What is Next.js? + - Comparing Next.js with other frameworks (e.g., React, Angular) + - Setting up the development environment + +**2. Getting Started with Next.js** + - Creating a new Next.js project + - Running the development server & Deploying + +**3. Pages and Routing** + - Creating pages in Next.js + - Understanding the file-based routing system + +**4. Static and Server-Side Rendering** + - Difference between static and server-side rendering + - Concept of Static and server-side rendering + +**5. Styling in Next.js** + - Using CSS in Next.js + - Integrating with CSS-in-JS libraries (e.g., styled-components, emotion) + +**6. API Routes** + - Creating API routes in Next.js + - Connecting API routes to a database + +### Intermediate Level + +**1. Data Fetching and Caching** + - Fetching data from APIs + - SWR (Stale-While-Revalidate) for data fetching and caching + - Using GraphQL with Next.js + - Handling data fetching errors + +**2. Authentication and Authorization** + - Implementing authentication with NextAuth.js + - JWT-based authentication + - Role-based access control + - Protecting routes and API endpoints + +**3. Middleware and Custom Server** + - Understanding and using middleware in Next.js + - Using middleware for logging, authentication, etc. + - Advanced routing techniques with a custom server + +**4. Internationalization (i18n)** + - Setting up internationalization in Next.js + - Loading and managing translations + - Handling dynamic content in different languages + +### Advanced Level + +**1. Advanced Data Fetching** + - Static generation with revalidation + - Combining static and dynamic data fetching + +**2. Advanced Routing Techniques** + - Dynamic API routes + - Customizing the Next.js router + +**3. Next.js and GraphQL** + - Setting up a GraphQL server with Next.js + - Using Apollo Client with Next.js + +**4. Advanced Server-Side Rendering** + - Customizing the server-side rendering process + - Optimizing SSR for performance + \ No newline at end of file diff --git a/courses/Next.Js/_category_.json b/courses/Next.Js/_category_.json new file mode 100644 index 000000000..206868ec0 --- /dev/null +++ b/courses/Next.Js/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Next.Js", + "position": 10, + "link": { + "type": "generated-index", + "description": "Learn MongoDB." + } + } \ No newline at end of file diff --git a/courses/Next.Js/advance-level/Advance-Routing/Customizing.md b/courses/Next.Js/advance-level/Advance-Routing/Customizing.md new file mode 100644 index 000000000..ee84157a1 --- /dev/null +++ b/courses/Next.Js/advance-level/Advance-Routing/Customizing.md @@ -0,0 +1,136 @@ +--- +id: lesson-2 +title: "Customizing the Next.js Router" +sidebar_label: Customizing the Next.js Router +sidebar_position: 2 +description: "Customizing the Next.js Router" +tags: [courses,Advance-level,FramWorks,Introduction] +--- + + + +Next.js allows you to customize the router to add additional functionalities or handle specific routing needs. + +1. **Using Custom Server with Express.js**: + ```javascript + // server.js + const express = require('express'); + const next = require('next'); + + const dev = process.env.NODE_ENV !== 'production'; + const app = next({ dev }); + const handle = app.getRequestHandler(); + + app.prepare().then(() => { + const server = express(); + + server.get('/custom-route', (req, res) => { + return app.render(req, res, '/custom', req.query); + }); + + server.all('*', (req, res) => { + return handle(req, res); + }); + + server.listen(3000, (err) => { + if (err) throw err; + console.log('> Ready on http://localhost:3000'); + }); + }); + ``` + +2. **Adding Custom Route to Next.js Router**: + ```javascript + // next.config.js + module.exports = { + async rewrites() { + return [ + { + source: '/custom-route', + destination: '/custom', + }, + ]; + }, + }; + ``` + +#### Route-Level Code Splitting + +Route-level code splitting ensures that only the necessary code for the current route is loaded, improving performance by reducing the initial load time. + +1. **Implementing Route-Level Code Splitting**: + - Next.js automatically splits your code into separate bundles for each page. Each page only loads the necessary code when it is accessed. + - You can leverage dynamic imports to further enhance code splitting: + ```javascript + // pages/index.js + import dynamic from 'next/dynamic'; + + const DynamicComponent = dynamic(() => import('../components/DynamicComponent')); + + export default function Home() { + return ( +
+

Home Page

+ +
+ ); + } + ``` + +2. **Using `dynamic` for Code Splitting with Custom Loading**: + ```javascript + // pages/index.js + import { useState } from 'react'; + import dynamic from 'next/dynamic'; + + const DynamicComponentWithCustomLoading = dynamic(() => import('../components/DynamicComponent'), { + loading: () =>

Loading...

, + }); + + export default function Home() { + const [loadDynamicComponent, setLoadDynamicComponent] = useState(false); + + const handleClick = () => { + setLoadDynamicComponent(true); + }; + return ( +
+

Home Page

+ + {loadDynamicComponent && } +
+ ); + } + ``` + **Output:** + +
+

Home Page

+ +

Switch Dynamic Content

+
+
\ No newline at end of file diff --git a/courses/Next.Js/advance-level/Advance-Routing/Dynamic-Route.md b/courses/Next.Js/advance-level/Advance-Routing/Dynamic-Route.md new file mode 100644 index 000000000..a0c3b3c73 --- /dev/null +++ b/courses/Next.Js/advance-level/Advance-Routing/Dynamic-Route.md @@ -0,0 +1,80 @@ +--- +id: lesson-1 +title: "Advanced Routing Techniques in Next.js" +sidebar_label: Advanced Routing Techniques +sidebar_position: 1 +description: "Advanced Routing Techniques in Next.js" +tags: [courses,Advance-level,FramWorks,Introduction] +--- + + +Advanced routing techniques in Next.js enable you to build more flexible and optimized applications. These techniques include dynamic API routes, middleware for route protection and redirects, customizing the Next.js router, and implementing route-level code splitting. + +#### Dynamic API Routes + +Dynamic API routes allow you to create API endpoints that can handle dynamic parameters. + +1. **Creating Dynamic API Routes**: + ```javascript + // pages/api/user/[id].js + export default function handler(req, res) { + const { + query: { id }, + method, + } = req; + + switch (method) { + case 'GET': + // Fetch user data + res.status(200).json({ id, name: `User ${id}` }); + break; + case 'PUT': + // Update user data + res.status(200).json({ id, name: `Updated User ${id}` }); + break; + default: + res.setHeader('Allow', ['GET', 'PUT']); + res.status(405).end(`Method ${method} Not Allowed`); + break; + } + } + ``` + +#### Middleware for Route Protection and Redirects + +Middleware can be used to protect routes and handle redirects based on certain conditions, such as user authentication. + +1. **Implementing Middleware for Route Protection**: + ```javascript + // middleware.js + import { NextResponse } from 'next/server'; + + export function middleware(req) { + const { pathname } = req.nextUrl; + + // Protect routes starting with /admin + if (pathname.startsWith('/admin')) { + const token = req.cookies.get('token'); + + if (!token) { + return NextResponse.redirect('/login'); + } + } + + return NextResponse.next(); + } + ``` + +2. **Adding Middleware to the Next.js Configuration**: + ```javascript + // next.config.js + module.exports = { + async rewrites() { + return { + beforeFiles: [ + { source: '/admin/:path*', destination: '/middleware' }, + ], + }; + }, + }; + ``` \ No newline at end of file diff --git a/courses/Next.Js/advance-level/Advance-Routing/_category_.json b/courses/Next.Js/advance-level/Advance-Routing/_category_.json new file mode 100644 index 000000000..f437e3cd3 --- /dev/null +++ b/courses/Next.Js/advance-level/Advance-Routing/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Advanced Routing", + "position": 2, + "link": { + "type": "generated-index", + "description": "Learn Next.Js Advance Routing Techniques." + } + } \ No newline at end of file diff --git a/courses/Next.Js/advance-level/Advance-data-fetching/_category_.json b/courses/Next.Js/advance-level/Advance-data-fetching/_category_.json new file mode 100644 index 000000000..8e35b9b57 --- /dev/null +++ b/courses/Next.Js/advance-level/Advance-data-fetching/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Advanced Data Fetching", + "position": 1, + "link": { + "type": "generated-index", + "description": "Learn Next.Js Advanced Data Fetching." + } + } \ No newline at end of file diff --git a/courses/Next.Js/advance-level/Advance-data-fetching/dynamic-generation.md b/courses/Next.Js/advance-level/Advance-data-fetching/dynamic-generation.md new file mode 100644 index 000000000..138bf557a --- /dev/null +++ b/courses/Next.Js/advance-level/Advance-data-fetching/dynamic-generation.md @@ -0,0 +1,191 @@ +--- +id: lesson-2 +title: "Combining Static and Dynamic Data Fetching" +sidebar_label: Combining Static and Dynamic Data Fetching +sidebar_position: 2 +description: "Combining Static and Dynamic Data Fetching" +tags: [courses,Advance-level,FramWorks,Introduction] +--- + + +You can combine static and dynamic data fetching to build more flexible and performant applications. + +1. **Combining Static Generation with Client-side Fetching**: + ```javascript + // pages/index.js + import { useEffect, useState } from 'react'; + + export async function getStaticProps() { + // Fetch static data + const res = await fetch('https://api.example.com/static-data'); + const staticData = await res.json(); + + return { + props: { + staticData, + }, + revalidate: 60, // Revalidate every 60 seconds + }; + } + + export default function Home({ staticData }) { + const [dynamicData, setDynamicData] = useState(null); + + function handleClick(){ + // Fetch dynamic data on client-side + fetch('https://api.example.com/dynamic-data') + .then((res) => res.json()) + .then((data) => setDynamicData(data)); + } + + return ( +
+

Combining Static and Dynamic Data Fetching

+

Static Data

+
{JSON.stringify(staticData, null, 2)}
+

Dynamic Data

+ + {dynamicData ? ( +
{JSON.stringify(dynamicData, null, 2)}
+ ) : ( +

Loading...

+ )} +
+ ); + } + ``` +**Output:** + +
+

Combining Static and Dynamic Data Fetching

+

Static Data

+
{`${JSON.stringify([{ id:"1",
+                    name:"siva",
+                    info:"Developer"
+                   },{
+                     id:"2",
+                     name:"Kumar",
+                     info:"Developer"
+                   }],null,2)}`}
+

Dynamic Data

+ +
+

+

+      
+
+#### Optimizing Data Fetching for Performance + +1. **Minimizing API Calls**: + - Cache data at various levels (CDN, server, client) to minimize API calls. + - Use tools like `SWR` or `React Query` to manage caching and synchronization of data. + +2. **Using Incremental Static Regeneration (ISR)**: + - ISR allows pages to be regenerated incrementally without rebuilding the entire site. + ```javascript + // pages/index.js + export async function getStaticProps() { + const res = await fetch('https://api.example.com/data'); + const data = await res.json(); + + return { + props: { + data, + }, + revalidate: 60, // Revalidate every 60 seconds + }; + } + + export default function Home({ data }) { + return ( +
+

Optimized Data Fetching

+
{JSON.stringify(data, null, 2)}
+
+ ); + } + ``` + +**Output:** + +
+

Optimized Data Fetching

+
{`${JSON.stringify([{ id:"1",
+                    name:"siva",
+                    info:"Developer"
+                   },{
+                     id:"2",
+                     name:"Kumar",
+                     info:"Developer"
+                   }],null,2)}`}
+
+
+ +3. **Prefetching Data**: + - Prefetch data for links using the `next/link` component to improve navigation speed. + ```javascript + import Link from 'next/link'; + + export default function Home() { + return ( +
+

Home Page

+ + Go to About + +
+ ); + } + ``` + +**Output:** + +
+

Home Page

+ +
+
+ + +4. **Using SWR for Client-side Caching**: + - `SWR` (Stale-While-Revalidate) is a React Hooks library for data fetching that provides caching and revalidation. + ```javascript + import useSWR from 'swr'; + + const fetcher = (url) => fetch(url).then((res) => res.json()); + + export default function DataComponent() { + const { data, error } = useSWR('/api/data', fetcher); + + if (error) return
Failed to load
; + if (!data) return
Loading...
; + + return
Data: {JSON.stringify(data)}
; + } + ``` + diff --git a/courses/Next.Js/advance-level/Advance-data-fetching/static-generation.md b/courses/Next.Js/advance-level/Advance-data-fetching/static-generation.md new file mode 100644 index 000000000..bc4bc9e0a --- /dev/null +++ b/courses/Next.Js/advance-level/Advance-data-fetching/static-generation.md @@ -0,0 +1,100 @@ +--- +id: lesson-1 +title: "Advanced Data Fetching in Next.js" +sidebar_label: Advanced Data Fetching in Next.js +sidebar_position: 1 +description: "Advanced Data Fetching in Next.js" +tags: [courses,Advance-level,FramWorks,Introduction] +--- + + + +Next.js provides powerful data fetching capabilities to optimize the performance and scalability of your application. This involves using static generation with revalidation, server-side rendering with caching strategies, combining static and dynamic data fetching, and optimizing these processes for performance. + +#### Static Generation with Revalidation + +Static generation with revalidation allows you to generate static pages at build time and update them at runtime when necessary. + +1. **Setting up Static Generation with Revalidation**: + ```javascript + // pages/index.js + export async function getStaticProps() { + // Fetch data + const res = await fetch('https://api.example.com/data'); + const data = await res.json(); + + return { + props: { + data, + }, + revalidate: 10, // Revalidate every 10 seconds + }; + } + + export default function Home({ data }) { + return ( +
+

Static Generation with Revalidation

+
{JSON.stringify(data, null, 2)}
+
+ ); + } + ``` + + + +#### Server-side Rendering with Caching Strategies + +Server-side rendering (SSR) can be optimized using caching strategies to improve performance and reduce server load. + +1. **Setting up Server-side Rendering with Caching**: + ```javascript + // pages/ssr.js + export async function getServerSideProps(context) { + const res = await fetch('https://api.example.com/data'); + const data = await res.json(); + + context.res.setHeader('Cache-Control', 's-maxage=10, stale-while-revalidate'); + + return { + props: { + data, + }, + }; + } + + export default function SSR({ data }) { + return ( +
+

Server-side Rendering with Caching

+
{JSON.stringify(data, null, 2)}
+
+ ); + } + ``` + +2. **Using Cache-Control Headers**: + - `s-maxage=10`: Cache the response on the server for 10 seconds. + - `stale-while-revalidate`: Serve stale content while revalidating in the background. + +**Output:** + +
+

Static Generation with Revalidation

+ +
+

+      
+
\ No newline at end of file diff --git a/courses/Next.Js/advance-level/Advance-server-side-render/SSR.md b/courses/Next.Js/advance-level/Advance-server-side-render/SSR.md new file mode 100644 index 000000000..d6a40f93f --- /dev/null +++ b/courses/Next.Js/advance-level/Advance-server-side-render/SSR.md @@ -0,0 +1,160 @@ +--- +id: lesson-2 +title: "Optimizing SSR for Performance" +sidebar_label: Optimizing SSR +sidebar_position: 2 +description: "Optimizing SSR for Performance" +tags: [courses,Advance-level,FramWorks,Introduction] +--- + + + +1. **Caching Responses**: + - Use caching strategies to reduce the load on the server. + ```javascript + // pages/index.js + export async function getServerSideProps(context) { + const cache = new Map(); + const cacheKey = 'data'; + + if (cache.has(cacheKey)) { + return { + props: { + data: cache.get(cacheKey), + }, + }; + } + + const res = await fetch('https://api.example.com/data'); + const data = await res.json(); + cache.set(cacheKey, data); + + return { + props: { + data, + }, + }; + } + ``` + +2. **Optimizing Data Fetching**: + - Fetch only necessary data and minimize the amount of data sent to the client. + ```javascript + // pages/index.js + export async function getServerSideProps(context) { + const res = await fetch('https://api.example.com/data?fields=id,name'); + const data = await res.json(); + + return { + props: { + data, + }, + }; + } + ``` + +3. **Using Static Generation with Revalidation**: + - Use static generation with incremental static regeneration (ISR) for frequently updated data. + ```javascript + // pages/index.js + export async function getStaticProps() { + const res = await fetch('https://api.example.com/data'); + const data = await res.json(); + + return { + props: { + data, + }, + revalidate: 60, // Revalidate every 60 seconds + }; + } + + export default function Home({ data }) { + return ( +
+

Data with ISR

+
{JSON.stringify(data, null, 2)}
+
+ ); + } + ``` + +#### SSR with Authentication and Session Management + +1. **Implementing Authentication**: + - Use a library like `next-auth` to handle authentication. + ```bash + npm install next-auth + ``` + + ```javascript + // pages/api/auth/[...nextauth].js + import NextAuth from 'next-auth'; + import Providers from 'next-auth/providers'; + + export default NextAuth({ + providers: [ + Providers.Google({ + clientId: process.env.GOOGLE_CLIENT_ID, + clientSecret: process.env.GOOGLE_CLIENT_SECRET, + }), + ], + }); + ``` + +2. **Protecting Routes**: + - Use `getServerSideProps` to check authentication status. + ```javascript + // pages/secure-page.js + import { getSession } from 'next-auth/react'; + + export async function getServerSideProps(context) { + const session = await getSession(context); + + if (!session) { + return { + redirect: { + destination: '/api/auth/signin', + permanent: false, + }, + }; + } + + return { + props: { session }, + }; + } + + export default function SecurePage({ session }) { + return ( +
+

Secure Page

+

Welcome, {session.user.name}!

+
+ ); + } + ``` + +3. **Session Management**: + - Manage sessions using cookies or tokens. + ```javascript + // lib/auth.js + import { parseCookies, setCookie, destroyCookie } from 'nookies'; + + export function getAuthCookie(context) { + const cookies = parseCookies(context); + return cookies.auth; + } + + export function setAuthCookie(context, token) { + setCookie(context, 'auth', token, { + maxAge: 30 * 24 * 60 * 60, + path: '/', + }); + } + + export function destroyAuthCookie(context) { + destroyCookie(context, 'auth'); + } + ``` + \ No newline at end of file diff --git a/courses/Next.Js/advance-level/Advance-server-side-render/_category_.json b/courses/Next.Js/advance-level/Advance-server-side-render/_category_.json new file mode 100644 index 000000000..ac7ed71b4 --- /dev/null +++ b/courses/Next.Js/advance-level/Advance-server-side-render/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Advanced Server-side Rendering", + "position": 4, + "link": { + "type": "generated-index", + "description": "Learn Advanced Server-side Rendering." + } + } \ No newline at end of file diff --git a/courses/Next.Js/advance-level/Advance-server-side-render/customize.md b/courses/Next.Js/advance-level/Advance-server-side-render/customize.md new file mode 100644 index 000000000..457ae489f --- /dev/null +++ b/courses/Next.Js/advance-level/Advance-server-side-render/customize.md @@ -0,0 +1,142 @@ +--- +id: lesson-1 +title: "Advanced Server-Side Rendering (SSR) in Next.js" +sidebar_label: Advanced SSR +sidebar_position: 1 +description: "Advanced Server-Side Rendering (SSR) in Next.js" +tags: [courses,Advance-level,FramWorks,Introduction] +--- + + +Server-Side Rendering (SSR) in Next.js allows for dynamic data fetching and rendering on the server, providing a performant and SEO-friendly experience. This guide covers customizing the SSR process, handling complex data fetching and state management, optimizing SSR for performance, and implementing SSR with authentication and session management. + +#### Customizing the Server-Side Rendering Process + +1. **Customizing `getServerSideProps`**: + - Use `getServerSideProps` to fetch data on each request. + ```javascript + // pages/index.js + export async function getServerSideProps(context) { + const res = await fetch('https://api.example.com/data'); + const data = await res.json(); + + return { + props: { + data, + }, + }; + } + + export default function Home({ data }) { + return ( +
+

Data from Server

+
{JSON.stringify(data, null, 2)}
+
+ ); + } + ``` + +2. **Handling Complex Data Fetching**: + - Perform multiple data fetches or handle errors within `getServerSideProps`. + ```javascript + // pages/index.js + export async function getServerSideProps(context) { + try { + const [res1, res2] = await Promise.all([ + fetch('https://api.example.com/data1'), + fetch('https://api.example.com/data2'), + ]); + const data1 = await res1.json(); + const data2 = await res2.json(); + + return { + props: { + data1, + data2, + }, + }; + } catch (error) { + return { + props: { + error: 'Failed to fetch data', + }, + }; + } + } + + export default function Home({ data1, data2, error }) { + if (error) { + return

{error}

; + } + + return ( +
+

Data from Server

+
{JSON.stringify(data1, null, 2)}
+
{JSON.stringify(data2, null, 2)}
+
+ ); + } + ``` + +#### Handling Complex Data Fetching and State Management + +1. **Integrating Redux with SSR**: + - Set up Redux store and integrate with `getServerSideProps`. + ```javascript + // store.js + import { createStore } from 'redux'; + import rootReducer from './reducers'; + + export const initializeStore = (preloadedState) => { + return createStore(rootReducer, preloadedState); + }; + ``` + + ```javascript + // pages/_app.js + import { Provider } from 'react-redux'; + import { initializeStore } from '../store'; + + export default function App({ Component, pageProps }) { + const store = initializeStore(pageProps.initialReduxState); + + return ( + + + + ); + } + ``` + + ```javascript + // pages/index.js + import { useSelector } from 'react-redux'; + import { initializeStore } from '../store'; + import { fetchData } from '../actions'; + + export async function getServerSideProps() { + const reduxStore = initializeStore(); + const { dispatch } = reduxStore; + + await dispatch(fetchData()); + + return { + props: { + initialReduxState: reduxStore.getState(), + }, + }; + } + + export default function Home() { + const data = useSelector((state) => state.data); + + return ( +
+

Data from Redux Store

+
{JSON.stringify(data, null, 2)}
+
+ ); + } + ``` \ No newline at end of file diff --git a/courses/Next.Js/advance-level/GraphQL/Introduction.md b/courses/Next.Js/advance-level/GraphQL/Introduction.md new file mode 100644 index 000000000..565f99fe3 --- /dev/null +++ b/courses/Next.Js/advance-level/GraphQL/Introduction.md @@ -0,0 +1,106 @@ +--- +id: lesson-1 +title: "Next.js and GraphQL" +sidebar_label: GraphQL +sidebar_position: 1 +description: "Next.js and GraphQL" +tags: [courses,Advance-level,FramWorks,Introduction] +--- + + +Integrating GraphQL with Next.js allows you to leverage the powerful capabilities of GraphQL for querying data while enjoying the benefits of Next.js, such as server-side rendering and static site generation. Here's a guide to setting up a GraphQL server with Next.js, querying GraphQL APIs from Next.js, using Apollo Client, and advanced GraphQL features. + +#### Setting up a GraphQL Server with Next.js + +1. **Install Required Packages**: + ```bash + npm install apollo-server-micro graphql + ``` + +2. **Create a GraphQL Server**: + ```javascript + // pages/api/graphql.js + import { ApolloServer, gql } from 'apollo-server-micro'; + + const typeDefs = gql` + type Query { + hello: String + } + `; + + const resolvers = { + Query: { + hello: () => 'Hello, world!', + }, + }; + + const apolloServer = new ApolloServer({ typeDefs, resolvers }); + + export const config = { + api: { + bodyParser: false, + }, + }; + + const startServer = apolloServer.start(); + + export default async function handler(req, res) { + await startServer; + await apolloServer.createHandler({ path: '/api/graphql' })(req, res); + } + ``` + +3. **Test the GraphQL Server**: + - Start your Next.js development server and navigate to `/api/graphql`. + - Use a tool like GraphQL Playground or Insomnia to send queries to your GraphQL endpoint. + +#### Querying GraphQL APIs from Next.js + +1. **Install Apollo Client**: + ```bash + npm install @apollo/client graphql + ``` + +2. **Set up Apollo Client**: + ```javascript + // lib/apolloClient.js + import { ApolloClient, InMemoryCache } from '@apollo/client'; + + const client = new ApolloClient({ + uri: '/api/graphql', + cache: new InMemoryCache(), + }); + + export default client; + ``` + +3. **Query GraphQL APIs in a Next.js Page**: + ```javascript + // pages/index.js + import { gql } from '@apollo/client'; + import client from '../lib/apolloClient'; + + export async function getStaticProps() { + const { data } = await client.query({ + query: gql` + query { + hello + } + `, + }); + + return { + props: { + message: data.hello, + }, + }; + } + + export default function Home({ message }) { + return ( +
+

{message}

+
+ ); + } + ``` \ No newline at end of file diff --git a/courses/Next.Js/advance-level/GraphQL/_category_.json b/courses/Next.Js/advance-level/GraphQL/_category_.json new file mode 100644 index 000000000..f21c26ee3 --- /dev/null +++ b/courses/Next.Js/advance-level/GraphQL/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Next.js and GraphQL", + "position": 3, + "link": { + "type": "generated-index", + "description": "Learn Next.Js and GraphQL." + } + } \ No newline at end of file diff --git a/courses/Next.Js/advance-level/GraphQL/apollo-client.md b/courses/Next.Js/advance-level/GraphQL/apollo-client.md new file mode 100644 index 000000000..c073cf05c --- /dev/null +++ b/courses/Next.Js/advance-level/GraphQL/apollo-client.md @@ -0,0 +1,226 @@ +--- +id: lesson-2 +title: "Using Apollo Client with Next.js" +sidebar_label: Apollo Client +sidebar_position: 2 +description: "Using Apollo Client with Next.js" +tags: [courses,Advance-level,FramWorks,Introduction] +--- + + +1. **Create an Apollo Provider**: + ```javascript + // lib/apolloClient.js + import { ApolloClient, InMemoryCache, ApolloProvider } from '@apollo/client'; + + const client = new ApolloClient({ + uri: '/api/graphql', + cache: new InMemoryCache(), + }); + + export function ApolloProviderWrapper({ children }) { + return {children}; + } + ``` + +2. **Wrap the App Component**: + ```javascript + // pages/_app.js + import { ApolloProviderWrapper } from '../lib/apolloClient'; + + function MyApp({ Component, pageProps }) { + return ( + + + + ); + } + + export default MyApp; + ``` + +3. **Query Data in Components**: + ```javascript + // components/Hello.js + import { useQuery, gql } from '@apollo/client'; + + const HELLO_QUERY = gql` + query { + hello + } + `; + + export default function Hello() { + const { loading, error, data } = useQuery(HELLO_QUERY); + + if (loading) return

Loading...

; + if (error) return

Error: {error.message}

; + + return

{data.hello}

; + } + ``` + +4. **Use the Component**: + ```javascript + // pages/index.js + import Hello from '../components/Hello'; + + export default function Home() { + return ( +
+ +
+ ); + } + ``` + +#### Advanced GraphQL Features (Subscriptions, Caching) + +1. **Setting Up Subscriptions**: + - For subscriptions, you need to set up a WebSocket server. First, install the required packages: + ```bash + npm install subscriptions-transport-ws @apollo/client graphql-ws + ``` + + - Configure your Apollo Server to support subscriptions: + ```javascript + // pages/api/graphql.js + import { ApolloServer, gql } from 'apollo-server-micro'; + import { useServer } from 'graphql-ws/lib/use/ws'; + import { WebSocketServer } from 'ws'; + + const typeDefs = gql` + type Query { + hello: String + } + type Subscription { + time: String + } + `; + + const resolvers = { + Query: { + hello: () => 'Hello, world!', + }, + Subscription: { + time: { + subscribe: (_, __, { pubsub }) => { + setInterval(() => pubsub.publish('TIME', { time: new Date().toISOString() }), 1000); + return pubsub.asyncIterator('TIME'); + }, + }, + }, + }; + + const pubsub = new PubSub(); + const apolloServer = new ApolloServer({ typeDefs, resolvers, context: { pubsub } }); + + export const config = { + api: { + bodyParser: false, + }, + }; + + const startServer = apolloServer.start(); + + export default async function handler(req, res) { + await startServer; + await apolloServer.createHandler({ path: '/api/graphql' })(req, res); + } + + // Setup WebSocket server + const wsServer = new WebSocketServer({ port: 4000 }); + useServer({ schema: apolloServer.schema }, wsServer); + ``` + + - Connect to the subscription server in your client: + ```javascript + // lib/apolloClient.js + import { ApolloClient, InMemoryCache, ApolloProvider, split } from '@apollo/client'; + import { WebSocketLink } from '@apollo/client/link/ws'; + import { createHttpLink } from '@apollo/client'; + import { getMainDefinition } from '@apollo/client/utilities'; + + const httpLink = createHttpLink({ + uri: '/api/graphql', + }); + + const wsLink = new WebSocketLink({ + uri: 'ws://localhost:4000/graphql', + options: { + reconnect: true, + }, + }); + + const splitLink = split( + ({ query }) => { + const definition = getMainDefinition(query); + return ( + definition.kind === 'OperationDefinition' && definition.operation === 'subscription' + ); + }, + wsLink, + httpLink + ); + + const client = new ApolloClient({ + link: splitLink, + cache: new InMemoryCache(), + }); + + export function ApolloProviderWrapper({ children }) { + return {children}; + } + ``` + + - Use subscriptions in your component: + ```javascript + // components/Time.js + import { useSubscription, gql } from '@apollo/client'; + + const TIME_SUBSCRIPTION = gql` + subscription { + time + } + `; + + export default function Time() { + const { data, loading } = useSubscription(TIME_SUBSCRIPTION); + + if (loading) return

Loading...

; + + return

Current time: {data.time}

; + } + ``` + +2. **Optimizing Caching with Apollo Client**: + - Configure cache policies in Apollo Client: + ```javascript + // lib/apolloClient.js + import { ApolloClient, InMemoryCache, ApolloProvider } from '@apollo/client'; + + const client = new ApolloClient({ + uri: '/api/graphql', + cache: new InMemoryCache({ + typePolicies: { + Query: { + fields: { + hello: { + read(existing) { + return existing; + }, + }, + }, + }, + }, + }), + }); + + export function ApolloProviderWrapper({ children }) { + return {children}; + } + ``` + +3. **Using Advanced GraphQL Features**: + - Utilize Apollo Client's built-in features for caching, pagination, optimistic UI updates, etc. + - Refer to Apollo Client documentation for detailed examples and advanced use cases: [Apollo Client Docs](https://www.apollographql.com/docs/react/) \ No newline at end of file diff --git a/courses/Next.Js/advance-level/_category_.json b/courses/Next.Js/advance-level/_category_.json new file mode 100644 index 000000000..cd2d95485 --- /dev/null +++ b/courses/Next.Js/advance-level/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Advanced Level", + "position": 3, + "link": { + "type": "generated-index", + "description": "Learn Next.Js Advance Techniques." + } + } \ No newline at end of file diff --git a/courses/Next.Js/beginner-level/Introduction/Frameworks.md b/courses/Next.Js/beginner-level/Introduction/Frameworks.md new file mode 100644 index 000000000..fd7bac29a --- /dev/null +++ b/courses/Next.Js/beginner-level/Introduction/Frameworks.md @@ -0,0 +1,22 @@ +--- +id: lesson-2 +title: "Comparing Next.js with Other Frameworks" +sidebar_label: Next.js with Frameworks +sidebar_position: 2 +description: "Comparing Next.js with Other Frameworks" +tags: [courses,beginner-level,FramWorks,Introduction] +--- + + +| **Feature** | **React** | **Next.js** | **Angular** | **Vue/Nuxt.js** | +|--------------------|---------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------| +| **Type** | Library for building UIs | Framework built on top of React providing SSR, SSG, and file-based routing | Full-fledged framework for building single-page applications | Vue: Progressive framework for building UIs
Nuxt.js: Framework built on Vue providing SSR, SSG | +| **Development** | Focuses on the view layer, requires additional libraries for routing, SSR | Simplifies development with out-of-the-box SSR, SSG, and file-based routing | Complete set of tools, more opinionated structure | Vue: Similar to React with component-based architecture
Nuxt.js: Similar features to Next.js | +| **Flexibility** | High, requires manual setup for routing, state management, SSR | High, but provides more out-of-the-box features, simplifying setup | Less flexibility, more opinionated | Vue: High flexibility
Nuxt.js: Simplifies setup with out-of-the-box features | +| **Language** | JavaScript | JavaScript | TypeScript (default) | Vue: JavaScript
Nuxt.js: JavaScript | +| **Server-Side Rendering (SSR)** | Requires additional setup | Built-in SSR | Possible, but not as straightforward | Built-in SSR with Nuxt.js | +| **Static Site Generation (SSG)** | Requires additional setup | Built-in SSG | Possible, but not as straightforward | Built-in SSG with Nuxt.js | +| **Routing** | Requires a library like React Router | File-based routing | Built-in | Vue: Requires Vue Router
Nuxt.js: File-based routing | +| **State Management** | Requires a library like Redux or Context API | Uses React state management, can integrate with libraries like Redux | Built-in with services and RxJS | Vue: Requires Vuex for state management
Nuxt.js: Integrates with Vuex | +| **Learning Curve** | Moderate, requires understanding of additional libraries | Lower compared to React alone, due to built-in features | Steeper learning curve due to more complex, opinionated framework | Vue: Moderate learning curve
Nuxt.js: Lower compared to Vue alone, due to built-in features | + \ No newline at end of file diff --git a/courses/Next.Js/beginner-level/Introduction/_category_.json b/courses/Next.Js/beginner-level/Introduction/_category_.json new file mode 100644 index 000000000..713020a21 --- /dev/null +++ b/courses/Next.Js/beginner-level/Introduction/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Introduction", + "position": 1, + "link": { + "type": "generated-index", + "description": "Let's Start with Next.Js." + } + } \ No newline at end of file diff --git a/courses/Next.Js/beginner-level/Introduction/introduction.md b/courses/Next.Js/beginner-level/Introduction/introduction.md new file mode 100644 index 000000000..368caf8b1 --- /dev/null +++ b/courses/Next.Js/beginner-level/Introduction/introduction.md @@ -0,0 +1,31 @@ +--- +id: lesson-1 +title: "Introduction to Next.js" +sidebar_label: Introduction +sidebar_position: 1 +description: "Introduction to Next.js" +tags: [courses,beginner-level,FramWorks,Introduction] +--- + + +#### What is Next.js? + +**Next.js** is a React framework that enables server-side rendering and static site generation for React applications. Developed by Vercel, it aims to provide a seamless developer experience while enhancing performance, scalability, and SEO. Next.js builds on top of React and provides a number of additional features to improve the development process and application performance. + +:::note +#### Benefits + +1. **Server-Side Rendering (SSR)**: Next.js enables server-side rendering, which allows pages to be pre-rendered on the server and sent to the client as fully rendered HTML. This improves initial load times and SEO. + +2. **Static Site Generation (SSG)**: Next.js can generate static HTML at build time for pages that don't need to be rendered on every request. This results in fast load times and efficient performance. + +3. **Automatic Code Splitting**: Next.js automatically splits code into smaller bundles that are loaded only when needed, optimizing page load times and performance. + +4. **API Routes**: Next.js allows you to create API endpoints within the same application, simplifying the process of building full-stack applications. + +5. **Optimized Performance**: With features like automatic static optimization, image optimization, and lazy loading, Next.js applications are highly performant. + +6. **Built-in CSS and Sass Support**: Next.js has built-in support for importing CSS and Sass files, making it easy to style your applications. + +7. **Developer Experience**: Features like fast refresh, which provides instantaneous feedback on edits without losing component state, make the development process more efficient and enjoyable. +::: \ No newline at end of file diff --git a/courses/Next.Js/beginner-level/Introduction/settingUp.md b/courses/Next.Js/beginner-level/Introduction/settingUp.md new file mode 100644 index 000000000..27efda2f0 --- /dev/null +++ b/courses/Next.Js/beginner-level/Introduction/settingUp.md @@ -0,0 +1,39 @@ +--- +id: lesson-3 +title: "Setting Up the Development Environment" +sidebar_label: Setup +sidebar_position: 3 +description: "Setting Up the Development Environment" +tags: [courses,beginner-level,FramWorks,Introduction] +--- + +To get started with Next.js, you'll need Node.js and npm (or yarn) installed on your system. Follow these steps to set up a Next.js development environment: + +1. **Install Node.js**: + - Download and install Node.js from [nodejs.org](https://nodejs.org/). + +2. **Create a New Next.js Application**: + - Open your terminal and run the following command to create a new Next.js project: + ```bash + npx create-next-app@latest my-next-app + # or + yarn create next-app my-next-app + ``` + +3. **Navigate to the Project Directory**: + - Change to the project directory: + ```bash + cd my-next-app + ``` + +4. **Start the Development Server**: + - Run the development server: + ```bash + npm run dev + # or + yarn dev + ``` + - Open your browser and navigate to [http://localhost:3000](http://localhost:3000) to see your Next.js application running. + + + ![Screenshot from 2024-07-20 07-58-50](https://github.com/user-attachments/assets/5dbec61f-cd1f-458f-9856-e8f9d82af8de) \ No newline at end of file diff --git a/courses/Next.Js/beginner-level/Pages-and-routing/FIlebase-Routing.md b/courses/Next.Js/beginner-level/Pages-and-routing/FIlebase-Routing.md new file mode 100644 index 000000000..4d267dcd7 --- /dev/null +++ b/courses/Next.Js/beginner-level/Pages-and-routing/FIlebase-Routing.md @@ -0,0 +1,91 @@ +--- +id: lesson-2 +title: "Understanding the File-Based Routing System" +sidebar_label: File-Based Routing System +sidebar_position: 2 +description: "Understanding the File-Based Routing System" +tags: [courses,beginner-level,FramWorks,Introduction] +--- + + +Next.js uses a file-based routing system, where the file structure inside the `src/pages` directory defines the routes of the application. + +1. **File and Folder Structure**: + - Each file in `src/pages` represents a unique route based on its name and path. + - Folders within `src/pages` can contain additional pages and create nested routes. + +2. **Example Structure**: + ``` + src/pages/ + ├── about.js // Maps to /about + ├── index.js // Maps to / + ├── blog/ + │ ├── index.js // Maps to /blog + │ └── [id].js // Maps to /blog/:id + ├── contact.js // Maps to /contact + └── products/ + ├── index.js // Maps to /products + └── [id].js // Maps to /products/:id + ``` + +3. **Dynamic Routing**: + - Dynamic routes can be created using square brackets in the file name. For example, `[id].js` creates a dynamic route that matches any value in place of `id`: + ```javascript + // src/pages/blog/[id].js + import { useRouter } from 'next/router'; + + export default function BlogPost() { + const router = useRouter(); + const { id } = router.query; + + return

Blog Post {id}

; + } + ``` + - This file will be accessible at URLs like `/blog/1`, `/blog/2`, etc., where `1` and `2` are dynamic parameters. + +#### Nested Routes + +Nested routes can be achieved by creating folders within the `src/pages` directory and adding files within those folders. + +1. **Nested Route Example**: + - Create a `products` directory inside `src/pages`: + ``` + src/pages/products/ + ├── index.js // Maps to /products + └── [id].js // Maps to /products/:id + ``` + +2. **Nested Index Page**: + - The `index.js` file inside the `products` directory maps to the `/products` route: + ```javascript + // src/pages/products/index.js + export default function Products() { + return

Products Page

; + } + ``` + +
+

Products Page

+
+
+ + +3. **Nested Dynamic Route**: + - The `[id].js` file inside the `products` directory maps to dynamic routes like `/products/1`, `/products/2`, etc.: + ```javascript + // src/pages/products/[id].js + import { useRouter } from 'next/router'; + + export default function Product() { + const router = useRouter(); + const { id } = router.query; + + return

Product {id}

; + } + ``` + +
+

Products 3

+
+
+ \ No newline at end of file diff --git a/courses/Next.Js/beginner-level/Pages-and-routing/_category_.json b/courses/Next.Js/beginner-level/Pages-and-routing/_category_.json new file mode 100644 index 000000000..cb7010da8 --- /dev/null +++ b/courses/Next.Js/beginner-level/Pages-and-routing/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Pages and Routing", + "position": 3, + "link": { + "type": "generated-index", + "description": "Learn to Routing." + } + } \ No newline at end of file diff --git a/courses/Next.Js/beginner-level/Pages-and-routing/creating-pages.md b/courses/Next.Js/beginner-level/Pages-and-routing/creating-pages.md new file mode 100644 index 000000000..c6cb8567d --- /dev/null +++ b/courses/Next.Js/beginner-level/Pages-and-routing/creating-pages.md @@ -0,0 +1,45 @@ +--- +id: lesson-1 +title: "Pages and Routing in Next.js" +sidebar_label: Pages and Routing +sidebar_position: 1 +description: "Pages and Routing in Next.js" +tags: [courses,beginner-level,FramWorks,Introduction] +--- + + +#### Creating Pages in Next.js + +In Next.js, pages are React components that are stored in the `src/pages` directory. Each file in this directory corresponds to a route in the application. + +1. **Basic Page Creation**: + - To create a new page, add a new file to the `src/pages` directory. For example, to create an "About" page, create `src/pages/about.js`: + ```javascript + // src/pages/about.js + export default function About() { + return

About Us

; + } + ``` + - This file will be accessible at the `/about` URL. + + +
+

About Us

+
+
+ +2. **Home Page**: + - The default home page is created by adding `index.js` to the `src/pages` directory: + ```javascript + // src/pages/index.js + export default function Home() { + return

Welcome to Our Site

; + } + ``` + - This file will be accessible at the root URL `/`. + + +
+

Welcome to Our Site

+
+
\ No newline at end of file diff --git a/courses/Next.Js/beginner-level/Routes/Database.md b/courses/Next.Js/beginner-level/Routes/Database.md new file mode 100644 index 000000000..12dc0c4ff --- /dev/null +++ b/courses/Next.Js/beginner-level/Routes/Database.md @@ -0,0 +1,140 @@ +--- +id: lesson-2 +title: "Connecting API Routes to a Database" +sidebar_label: Database Connection +sidebar_position: 2 +description: "Connecting API Routes to a Database" +tags: [courses,beginner-level,FramWorks,Introduction] +--- + + +You can connect your API routes to a database using popular database libraries like `mongoose` for MongoDB or `prisma` for SQL databases. Below is an example using MongoDB and Mongoose. + +1. **Install Mongoose**: + ```bash + npm install mongoose + ``` + +2. **Create a Database Connection Helper**: + - Create a `src/lib/dbConnect.js` file to manage the database connection: + ```javascript + // src/lib/dbConnect.js + import mongoose from 'mongoose'; + + const MONGODB_URI = process.env.MONGODB_URI; + + if (!MONGODB_URI) { + throw new Error( + 'Please define the MONGODB_URI environment variable inside .env.local' + ); + } + + let cached = global.mongoose; + + if (!cached) { + cached = global.mongoose = { conn: null, promise: null }; + } + + async function dbConnect() { + if (cached.conn) { + return cached.conn; + } + + if (!cached.promise) { + const opts = { + useNewUrlParser: true, + useUnifiedTopology: true, + bufferCommands: false, + bufferMaxEntries: 0, + useFindAndModify: false, + useCreateIndex: true, + }; + + cached.promise = mongoose.connect(MONGODB_URI, opts).then((mongoose) => { + return mongoose; + }); + } + cached.conn = await cached.promise; + return cached.conn; + } + + export default dbConnect; + ``` + +3. **Create a Mongoose Model**: + - Create a `src/models/User.js` file for the User model: + ```javascript + // src/models/User.js + import mongoose from 'mongoose'; + + const UserSchema = new mongoose.Schema({ + name: { + type: String, + required: [true, 'Please provide a name'], + }, + email: { + type: String, + required: [true, 'Please provide an email'], + unique: true, + }, + }); + + export default mongoose.models.User || mongoose.model('User', UserSchema); + ``` + +4. **Use the Database in API Routes**: + - Update your API route to connect to the database and interact with the User model: + ```javascript + // src/pages/api/users.js + import dbConnect from '../../lib/dbConnect'; + import User from '../../models/User'; + + export default async function handler(req, res) { + const { method } = req; + + await dbConnect(); + + switch (method) { + case 'GET': + try { + const users = await User.find({}); + res.status(200).json({ success: true, data: users }); + } catch (error) { + res.status(400).json({ success: false, error }); + } + break; + case 'POST': + try { + const user = await User.create(req.body); + res.status(201).json({ success: true, data: user }); + } catch (error) { + res.status(400).json({ success: false, error }); + } + break; + default: + res.setHeader('Allow', ['GET', 'POST']); + res.status(405).end(`Method ${method} Not Allowed`); + } + } + ``` + +
+ Fetched user Details +
+ +
+
No results Found
+
+
\ No newline at end of file diff --git a/courses/Next.Js/beginner-level/Routes/Introduction.md b/courses/Next.Js/beginner-level/Routes/Introduction.md new file mode 100644 index 000000000..9ad05ac3c --- /dev/null +++ b/courses/Next.Js/beginner-level/Routes/Introduction.md @@ -0,0 +1,48 @@ +--- +id: lesson-1 +title: "API Routes in Next.js" +sidebar_label: API Routes +sidebar_position: 1 +description: "API Routes in Next.js" +tags: [courses,beginner-level,FramWorks,Introduction] +--- + +Next.js provides a simple way to create API routes that you can use to handle backend logic, such as interacting with a database or performing server-side operations. These routes can be created within the `src/pages/api` directory. + +#### Creating API Routes in Next.js + +1. **Basic API Route**: + - Create a new file in the `src/pages/api` directory. For example, create `hello.js`: + ```javascript + // src/pages/api/hello.js + export default function handler(req, res) { + res.status(200).json({ message: 'Hello, world!' }); + } + ``` + - This API route will be accessible at `/api/hello`. + +2. **Handling API Requests**: + - API routes have access to the request (`req`) and response (`res`) objects, allowing you to handle different HTTP methods (GET, POST, PUT, DELETE, etc.). + +3. **Example with Multiple Methods**: + ```javascript + // src/pages/api/users.js + export default function handler(req, res) { + const { method } = req; + + switch (method) { + case 'GET': + // Handle GET request + res.status(200).json({ message: 'GET request' }); + break; + case 'POST': + // Handle POST request + const data = req.body; + res.status(201).json({ message: 'User created', data }); + break; + default: + res.setHeader('Allow', ['GET', 'POST']); + res.status(405).end(`Method ${method} Not Allowed`); + } + } + ``` diff --git a/courses/Next.Js/beginner-level/Routes/_category_.json b/courses/Next.Js/beginner-level/Routes/_category_.json new file mode 100644 index 000000000..8fb15c2a6 --- /dev/null +++ b/courses/Next.Js/beginner-level/Routes/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "API Routes", + "position": 6, + "link": { + "type": "generated-index", + "description": "Learn Next.Js API Routes." + } + } \ No newline at end of file diff --git a/courses/Next.Js/beginner-level/Started/Running-development.md b/courses/Next.Js/beginner-level/Started/Running-development.md new file mode 100644 index 000000000..d46ffa81b --- /dev/null +++ b/courses/Next.Js/beginner-level/Started/Running-development.md @@ -0,0 +1,66 @@ +--- +id: lesson-2 +title: "Running the Development Server" +sidebar_label: Development Server +sidebar_position: 2 +description: "Learn Development Server" +tags: [courses,beginner-level,FramWorks,Introduction] +--- + + + +To run the development server and start your Next.js application: + +1. Navigate to the project directory: + ```bash + cd my-next-app + ``` + +2. Start the development server: + ```bash + npm run dev + # or + yarn dev + ``` + +3. Open your browser and navigate to [http://localhost:3000](http://localhost:3000). You should see your Next.js application running. + +#### Building and Deploying a Next.js App + +Next.js provides built-in commands to build and deploy your application. + +1. **Building the Application**: + - Run the following command to create an optimized production build: + ```bash + npm run build + # or + yarn build + ``` + - This will generate a `.next` directory containing the compiled application. + +2. **Starting the Production Server**: + - After building the application, you can start the production server: + ```bash + npm start + # or + yarn start + ``` + + ![Screenshot from 2024-07-20 07-58-50](https://github.com/user-attachments/assets/5dbec61f-cd1f-458f-9856-e8f9d82af8de) + +3. **Deploying the Application**: + - **Vercel**: Vercel is the company behind Next.js and provides seamless integration for deploying Next.js applications. + - Install the Vercel CLI: + ```bash + npm install -g vercel + ``` + - Deploy your application: + ```bash + vercel + ``` + - Follow the prompts to link your project to a Vercel account and deploy it. + + - **Other Hosting Providers**: Next.js can be deployed on various hosting providers like AWS, Azure, Google Cloud, and DigitalOcean. + - Deploy the `.next` directory along with your project files to your preferred hosting provider. + - Ensure the environment supports Node.js and configure the start command to `npm start` or `yarn start`. + \ No newline at end of file diff --git a/courses/Next.Js/beginner-level/Started/_category_.json b/courses/Next.Js/beginner-level/Started/_category_.json new file mode 100644 index 000000000..33c4c33a0 --- /dev/null +++ b/courses/Next.Js/beginner-level/Started/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Project Build & Deployment", + "position": 2, + "link": { + "type": "generated-index", + "description": "Project Build & Deployment." + } + } \ No newline at end of file diff --git a/courses/Next.Js/beginner-level/Started/creating-project.md b/courses/Next.Js/beginner-level/Started/creating-project.md new file mode 100644 index 000000000..44ed25dda --- /dev/null +++ b/courses/Next.Js/beginner-level/Started/creating-project.md @@ -0,0 +1,67 @@ +--- +id: lesson-1 +title: "Getting Started with Next.js" +sidebar_label: Understanding Project +sidebar_position: 1 +description: "Getting Started with Next.js" +tags: [courses,beginner-level,FramWorks,Introduction] +--- + + +#### Creating a New Next.js Project + +To create a new Next.js project, you'll need to have Node.js and npm (or yarn) installed on your system. Follow these steps to set up your project: + +1. **Install Node.js**: + - Download and install Node.js from [nodejs.org](https://nodejs.org/). + +2. **Create a New Next.js Application**: + - Open your terminal and run the following command to create a new Next.js project: + ```bash + npx create-next-app@latest my-next-app + # or + yarn create next-app my-next-app + ``` + + - This command will prompt you to name your project and choose some initial configuration options. Once completed, it will generate a new Next.js project in a directory named `my-next-app`. + +#### Project Structure Overview + +A typical Next.js project has the following structure: + +``` +my-next-app/ +├── node_modules/ +├── public/ +│ ├── favicon.ico +│ └── vercel.svg +├── src/ +│ ├── pages/ +│ │ ├── api/ +│ │ │ └── hello.js +│ │ ├── _app.js +│ │ ├── _document.js +│ │ └── index.js +│ ├── styles/ +│ │ ├── globals.css +│ │ └── Home.module.css +│ └── components/ +│ └── [Your components here] +├── .gitignore +├── package.json +├── README.md +└── next.config.js +``` + +:::note +**Key Directories and Files**: +- **`public/`**: Contains static assets like images, fonts, and other files that you want to serve directly. Files in this directory are accessible from the root URL. +- **`src/pages/`**: Each file in this directory automatically becomes a route. For example, `pages/index.js` maps to `/`, and `pages/about.js` maps to `/about`. + - **`_app.js`**: Customizes the default App component used by Next.js to initialize pages. + - **`_document.js`**: Customizes the default Document component, useful for augmenting the application's HTML and body tags. + - **`api/`**: Contains serverless functions that map to `/api/*` routes. +- **`src/styles/`**: Contains CSS files to style your application. +- **`src/components/`**: Contains React components used across your application. +- **`next.config.js`**: Customizes the Next.js configuration. +- **`package.json`**: Lists dependencies and scripts for your project. +::: \ No newline at end of file diff --git a/courses/Next.Js/beginner-level/Styling/Libraries.md b/courses/Next.Js/beginner-level/Styling/Libraries.md new file mode 100644 index 000000000..2e00f4ffb --- /dev/null +++ b/courses/Next.Js/beginner-level/Styling/Libraries.md @@ -0,0 +1,80 @@ +--- +id: lesson-2 +title: "Integrating with CSS-in-JS Libraries" +sidebar_label: CSS with Libraries +sidebar_position: 2 +description: "Integrating with CSS-in-JS Libraries" +tags: [courses,beginner-level,FramWorks,Introduction] +--- + + +Next.js supports popular CSS-in-JS libraries like styled-components and emotion. + +**Using styled-components**: + +1. **Install styled-components and babel-plugin-styled-components**: + ```bash + npm install styled-components + npm install --save-dev babel-plugin-styled-components + ``` + +2. **Create a `.babelrc` File**: + ```json + { + "presets": ["next/babel"], + "plugins": [["styled-components", { "ssr": true }]] + } + ``` + +3. **Use styled-components in a Component**: + ```javascript + // src/pages/index.js + import styled from 'styled-components'; + + const Title = styled.h1` + color: #0070f3; + font-size: 4rem; + `; + + export default function Home() { + return ( +
+ Welcome to Next.js! +
+ ); + } + ``` + +**Using emotion**: + +1. **Install emotion**: + ```bash + npm install @emotion/react @emotion/styled + ``` + +2. **Use emotion in a Component**: + ```javascript + // src/pages/index.js + /** @jsxImportSource @emotion/react */ + import { css } from '@emotion/react'; + import styled from '@emotion/styled'; + + const titleStyle = css` + color: #0070f3; + font-size: 4rem; + `; + + const Title = styled.h1` + color: #0070f3; + font-size: 4rem; + `; + + export default function Home() { + return ( +
+

Welcome to Next.js with emotion!

+ Styled with emotion! +
+ ); + } + ``` \ No newline at end of file diff --git a/courses/Next.Js/beginner-level/Styling/_category_.json b/courses/Next.Js/beginner-level/Styling/_category_.json new file mode 100644 index 000000000..ee33dce5e --- /dev/null +++ b/courses/Next.Js/beginner-level/Styling/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Styling in Next.js", + "position": 5, + "link": { + "type": "generated-index", + "description": "Styling in Next.js." + } + } \ No newline at end of file diff --git a/courses/Next.Js/beginner-level/Styling/css-styling.md b/courses/Next.Js/beginner-level/Styling/css-styling.md new file mode 100644 index 000000000..b60e33ad3 --- /dev/null +++ b/courses/Next.Js/beginner-level/Styling/css-styling.md @@ -0,0 +1,104 @@ +--- +id: lesson-1 +title: "Styling in Next.js" +sidebar_label: Styling +sidebar_position: 1 +description: "Styling in Next.js" +tags: [courses,beginner-level,FramWorks,Introduction] +--- + +Next.js offers several ways to style your applications, including using plain CSS, CSS Modules, Styled JSX, and integrating with popular CSS-in-JS libraries like styled-components and emotion. + +#### Using CSS in Next.js + +You can use global CSS files in your Next.js application by importing them in your `src/pages/_app.js` file. + +1. **Create a Global CSS File**: + - Create a CSS file in the `src/styles` directory, e.g., `globals.css`: + ```css + /* src/styles/globals.css */ + body { + margin: 0; + font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', + 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', + sans-serif; + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; + } + + code { + font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New', monospace; + } + ``` + +2. **Import the Global CSS File**: + - Import the CSS file in `src/pages/_app.js`: + ```javascript + // src/pages/_app.js + import '../styles/globals.css'; + + function MyApp({ Component, pageProps }) { + return ; + } + + export default MyApp; + ``` + +#### CSS Modules + +CSS Modules provide a way to scope CSS to a specific component, avoiding global namespace collisions. + +1. **Create a CSS Module File**: + - Create a CSS Module file, e.g., `Home.module.css`: + ```css + /* src/styles/Home.module.css */ + .container { + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + height: 100vh; + } + + .title { + font-size: 4rem; + color: #0070f3; + } + ``` + +2. **Import and Use the CSS Module in a Component**: + - Import and apply the styles in your component: + ```javascript + // src/pages/index.js + import styles from '../styles/Home.module.css'; + + export default function Home() { + return ( +
+

Welcome to Next.js!

+
+ ); + } + ``` + +#### Styled JSX + +Styled JSX is built into Next.js and allows you to write scoped CSS directly within your components. + +1. **Use Styled JSX in a Component**: + ```javascript + // src/pages/index.js + export default function Home() { + return ( +
+

Welcome to Next.js!

+ +
+ ); + } + ``` \ No newline at end of file diff --git a/courses/Next.Js/beginner-level/_category_.json b/courses/Next.Js/beginner-level/_category_.json new file mode 100644 index 000000000..38cbcaefb --- /dev/null +++ b/courses/Next.Js/beginner-level/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Begginer Level", + "position": 1, + "link": { + "type": "generated-index", + "description": "Learn Next.Js Begginer Techniques." + } + } \ No newline at end of file diff --git a/courses/Next.Js/beginner-level/static-and-serverSide/_category_.json b/courses/Next.Js/beginner-level/static-and-serverSide/_category_.json new file mode 100644 index 000000000..24a4337b2 --- /dev/null +++ b/courses/Next.Js/beginner-level/static-and-serverSide/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Static and Server-Side Rendering", + "position": 4, + "link": { + "type": "generated-index", + "description": "Learn Next.Js Static and Server-Side Rendering." + } + } \ No newline at end of file diff --git a/courses/Next.Js/beginner-level/static-and-serverSide/concept.md b/courses/Next.Js/beginner-level/static-and-serverSide/concept.md new file mode 100644 index 000000000..ca18bb498 --- /dev/null +++ b/courses/Next.Js/beginner-level/static-and-serverSide/concept.md @@ -0,0 +1,170 @@ +--- +id: lesson-2 +title: "Concepts of static and server-side rendering" +sidebar_label: Concepts +sidebar_position: 2 +description: "Concepts of static and server-side rendering" +tags: [courses,beginner-level,FramWorks,Introduction] +--- + +#### Implementing Static Generation (`getStaticProps`) + +`getStaticProps` is a Next.js function that allows you to fetch data at build time to pre-render a page. + +1. **Creating a Page with `getStaticProps`**: + ```javascript + // src/pages/posts/[id].js + import { useRouter } from 'next/router'; + + export async function getStaticProps({ params }) { + // Fetch data for the post using the id from params + const res = await fetch(`https://jsonplaceholder.typicode.com/posts/${params.id}`); + const post = await res.json(); + + return { + props: { + post, + }, + }; + } + + export async function getStaticPaths() { + // Specify dynamic routes to pre-render based on data + const res = await fetch('https://jsonplaceholder.typicode.com/posts'); + const posts = await res.json(); + + const paths = posts.map(post => ({ + params: { id: post.id.toString() }, + })); + + return { + paths, + fallback: false, + }; + } + + export default function Post({ post }) { + const router = useRouter(); + if (router.isFallback) { + return
Loading...
; + } + + return ( +
+

{post.title}

+

{post.body}

+
+ ); + } + ``` + +2. **Explanation**: + - `getStaticProps` fetches data at build time and passes it as props to the page component. + - `getStaticPaths` specifies the dynamic routes to be pre-rendered. + - `fallback: false` ensures that only the specified paths are generated at build time. + +#### Implementing Server-Side Rendering (`getServerSideProps`) + +`getServerSideProps` is a Next.js function that allows you to fetch data on each request to pre-render a page. + +1. **Creating a Page with `getServerSideProps`**: + ```javascript + // src/pages/profile.js + export async function getServerSideProps(context) { + // Fetch data on each request + const res = await fetch('https://jsonplaceholder.typicode.com/users/1'); + const profile = await res.json(); + + return { + props: { + profile, + }, + }; + } + + export default function Profile({ profile }) { + return ( +
+

{profile.name}

+

{profile.email}

+
+ ); + } + ``` + +
+

John

+

johnexample@gmail.com

+
+
+ +2. **Explanation**: + - `getServerSideProps` fetches data on each request and passes it as props to the page component. + - This method ensures that the page is always up-to-date with the latest data. + +#### Incremental Static Regeneration (ISR) + +ISR allows you to update static pages after they have been built, without requiring a full rebuild of the site. + +1. **Implementing ISR with `revalidate`**: + ```javascript + // src/pages/posts/[id].js + export async function getStaticProps({ params }) { + const res = await fetch(`https://jsonplaceholder.typicode.com/posts/${params.id}`); + const post = await res.json(); + + return { + props: { + post, + }, + revalidate: 10, // Revalidate the page every 10 seconds + }; + } + + export async function getStaticPaths() { + const res = await fetch('https://jsonplaceholder.typicode.com/posts'); + const posts = await res.json(); + + const paths = posts.map(post => ({ + params: { id: post.id.toString() }, + })); + + return { + paths, + fallback: true, + }; + } + + export default function Post({ post }) { + const router = useRouter(); + if (router.isFallback) { + return
Loading...
; + } + + return ( +
+

{post.title}

+

{post.body}

+
+ ); + } + ``` + +
+ Loading... +
+ +
+2. **Explanation**: + - `revalidate`: Specifies the number of seconds after which the page should be regenerated. + - With ISR, the page will be updated in the background after the specified time, providing fresh content without a full rebuild. + \ No newline at end of file diff --git a/courses/Next.Js/beginner-level/static-and-serverSide/introduction.md b/courses/Next.Js/beginner-level/static-and-serverSide/introduction.md new file mode 100644 index 000000000..f6a1584b5 --- /dev/null +++ b/courses/Next.Js/beginner-level/static-and-serverSide/introduction.md @@ -0,0 +1,21 @@ +--- +id: lesson-1 +title: "Static and Server-Side Rendering in Next.js" +sidebar_label: Static and Server-Side Rendering +sidebar_position: 1 +description: "Static and Server-Side Rendering in Next.js" +tags: [courses,beginner-level,FramWorks,Introduction] +--- + + +#### Difference Between Static and Server-Side Rendering + +**Static Rendering (Static Site Generation - SSG)**: +- **Pre-rendering**: Pages are generated at build time, and the HTML is created once and reused for each request. +- **Performance**: Faster since the content is pre-rendered and served as static files. +- **Use Cases**: Ideal for pages that do not require frequent updates, such as blogs, documentation, and marketing pages. + +**Server-Side Rendering (SSR)**: +- **On-Demand Rendering**: Pages are generated on each request, fetching data and rendering HTML dynamically. +- **Performance**: Slower compared to static rendering because the server must generate the HTML for each request. +- **Use Cases**: Suitable for pages that require real-time data or frequent updates, such as dashboards, user profiles, and dynamic content. From 6e7e52aa712f92237d3907ffb72352b76ae57b78 Mon Sep 17 00:00:00 2001 From: Sivaprasath <121082414+sivaprasath2004@users.noreply.github.com> Date: Sat, 20 Jul 2024 22:02:14 +0530 Subject: [PATCH 3/5] Update introduction.md --- .../static-and-serverSide/introduction.md | 101 ++++++++++++++++++ 1 file changed, 101 insertions(+) diff --git a/courses/Next.Js/beginner-level/static-and-serverSide/introduction.md b/courses/Next.Js/beginner-level/static-and-serverSide/introduction.md index f6a1584b5..7cf4a6cef 100644 --- a/courses/Next.Js/beginner-level/static-and-serverSide/introduction.md +++ b/courses/Next.Js/beginner-level/static-and-serverSide/introduction.md @@ -19,3 +19,104 @@ tags: [courses,beginner-level,FramWorks,Introduction] - **On-Demand Rendering**: Pages are generated on each request, fetching data and rendering HTML dynamically. - **Performance**: Slower compared to static rendering because the server must generate the HTML for each request. - **Use Cases**: Suitable for pages that require real-time data or frequent updates, such as dashboards, user profiles, and dynamic content. + +## Implementing Static Generation (`getStaticProps`) + +`getStaticProps` is a Next.js function that allows you to fetch data at build time to pre-render a page. + +1. **Creating a Page with `getStaticProps`**: + + ```javascript title="pages/posts/[id].js" + import { useRouter } from "next/router"; + + export async function getStaticProps({ params }) { + // Fetch data for the post using the id from params + const res = await fetch( + `https://jsonplaceholder.typicode.com/posts/${params.id}`, + ); + const post = await res.json(); + + return { + props: { + post, + }, + }; + } + + export async function getStaticPaths() { + // Specify dynamic routes to pre-render based on data + const res = await fetch("https://jsonplaceholder.typicode.com/posts"); + const posts = await res.json(); + + const paths = posts.map((post) => ({ + params: { id: post.id.toString() }, + })); + + return { + paths, + fallback: false, + }; + } + + export default function Post({ post }) { + const router = useRouter(); + if (router.isFallback) { + return
Loading...
; + } + + return ( +
+

{post.title}

+

{post.body}

+
+ ); + } + ``` + +2. **Explanation**: + + - `getStaticProps` fetches data at build time and passes it as props to the page component. + - `getStaticPaths` specifies the dynamic routes to be pre-rendered. + - `fallback: false` ensures that only the specified paths are generated at build time. + - `router.isFallback` checks if the page is in fallback mode and displays a loading indicator. + - The `Post` component displays the post title and body fetched from the API. + +## Implementing Server-Side Rendering (`getServerSideProps`) + +`getServerSideProps` is a Next.js function that allows you to fetch data on each request to pre-render a page. + +1. **Creating a Page with `getServerSideProps`**: + + ```javascript title="pages/user/[id].js" + import { useRouter } from "next/router"; + + export async function getServerSideProps({ params }) { + // Fetch user data using the id from params + const res = await fetch( + `https://jsonplaceholder.typicode.com/users/${params.id}`, + ); + const user = await res.json(); + + return { + props: { + user, + }, + }; + } + + export default function User({ user }) { + return ( +
+

{user.name}

+

Email: {user.email}

+
+ ); + } + ``` + +2. **Explanation**: + + - `getServerSideProps` fetches data on each request and passes it as props to the page component. + - The `User` component displays the user's name and email fetched from the API. + +In this lesson, you learned about static and server-side rendering in Next.js and how to implement them using `getStaticProps` and `getServerSideProps` functions. Static rendering is ideal for content that does not change frequently, while server-side rendering is suitable for real-time data and dynamic content. From 5b8537b5bd83c0a1b8a6cf8b860f4014e798e6ea Mon Sep 17 00:00:00 2001 From: Sivaprasath <121082414+sivaprasath2004@users.noreply.github.com> Date: Sat, 20 Jul 2024 22:04:34 +0530 Subject: [PATCH 4/5] Update settingUp.md --- .../beginner-level/Introduction/settingUp.md | 27 ++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/courses/Next.Js/beginner-level/Introduction/settingUp.md b/courses/Next.Js/beginner-level/Introduction/settingUp.md index 27efda2f0..fd92b0d68 100644 --- a/courses/Next.Js/beginner-level/Introduction/settingUp.md +++ b/courses/Next.Js/beginner-level/Introduction/settingUp.md @@ -36,4 +36,29 @@ To get started with Next.js, you'll need Node.js and npm (or yarn) installed on - Open your browser and navigate to [http://localhost:3000](http://localhost:3000) to see your Next.js application running. - ![Screenshot from 2024-07-20 07-58-50](https://github.com/user-attachments/assets/5dbec61f-cd1f-458f-9856-e8f9d82af8de) \ No newline at end of file + ![Screenshot from 2024-07-20 07-58-50](https://github.com/user-attachments/assets/5dbec61f-cd1f-458f-9856-e8f9d82af8de) + + 5. **Explore the Project Structure**: + + - Next.js projects have the following structure: + ``` + my-next-app/ + ├── .next/ # Build output + ├── node_modules/ # Node.js modules + ├── pages/ # Pages and routes + ├── public/ # Static assets + ├── styles/ # Global styles + ├── .gitignore # Git ignore file + ├── package.json # Project metadata + ├── README.md # Project README + ``` + +6. **Start Building Your Next.js Application**: + + - You're now ready to start building your Next.js application. Explore the project structure, create new pages, and customize your application as needed. + +By following these steps, you can set up a development environment for building Next.js applications and start creating modern web experiences with ease. Happy coding! + +## Additional Resources: + +- [Next.js Documentation](https://nextjs.org/docs) From 5ef723729202e7f58eab9ec87d41ec93d99886b3 Mon Sep 17 00:00:00 2001 From: Sivaprasath <121082414+sivaprasath2004@users.noreply.github.com> Date: Sat, 20 Jul 2024 22:06:18 +0530 Subject: [PATCH 5/5] Update introduction.md --- .../Introduction/introduction.md | 39 ++++++++++++++++++- 1 file changed, 38 insertions(+), 1 deletion(-) diff --git a/courses/Next.Js/beginner-level/Introduction/introduction.md b/courses/Next.Js/beginner-level/Introduction/introduction.md index 368caf8b1..01fccdfbf 100644 --- a/courses/Next.Js/beginner-level/Introduction/introduction.md +++ b/courses/Next.Js/beginner-level/Introduction/introduction.md @@ -28,4 +28,41 @@ tags: [courses,beginner-level,FramWorks,Introduction] 6. **Built-in CSS and Sass Support**: Next.js has built-in support for importing CSS and Sass files, making it easy to style your applications. 7. **Developer Experience**: Features like fast refresh, which provides instantaneous feedback on edits without losing component state, make the development process more efficient and enjoyable. -::: \ No newline at end of file +::: + + +## Why Learn Next.js? + +Learning Next.js offers several benefits for developers looking to build modern web applications: + +1. **Improved Performance**: Next.js provides server-side rendering and static site generation, resulting in faster load times and better SEO performance. +2. **Enhanced SEO**: Pre-rendered pages in Next.js improve search engine optimization by providing search engines with fully rendered HTML content. +3. **Simplified Development**: Next.js simplifies the development process by offering features like automatic code splitting, API routes, and built-in CSS support. +4. **Scalability**: Next.js applications are highly scalable and can handle increased traffic and data requirements effectively. +5. **Full-Stack Development**: Next.js allows developers to build full-stack applications by integrating API routes and server-side rendering with React components. +6. **Community and Ecosystem**: Next.js has a vibrant community and ecosystem, with extensive documentation, tutorials, and plugins available to support developers. +7. **Career Opportunities**: Learning Next.js can open up career opportunities as Next.js developers are in demand due to the framework's popularity and versatility. +8. **Modern Web Development**: Next.js is a modern framework that incorporates the latest web development practices and tools, making it a valuable skill for developers. +9. **Vercel Integration**: Next.js is developed by Vercel, which offers hosting and deployment services that seamlessly integrate with Next.js applications. +10. **React Compatibility**: Next.js is built on top of React, making it a natural choice for developers familiar with React who want to enhance their applications with server-side rendering and static site generation. +11. **Performance Monitoring**: Next.js provides built-in performance monitoring tools that help developers optimize their applications for speed and efficiency. +12. **Incremental Static Regeneration**: Next.js supports incremental static regeneration, allowing developers to update static pages without requiring a full rebuild of the site. +13. **Hybrid Static and Server-Side Rendering**: Next.js allows developers to combine static site generation with server-side rendering for optimal performance and flexibility. +14. **TypeScript Support**: Next.js has built-in support for TypeScript, enabling developers to write type-safe code and improve code quality and maintainability. +15. **Internationalization**: Next.js provides built-in support for internationalization, making it easy to create multilingual applications with localized content. +16. **Authentication and Authorization**: Next.js offers solutions for implementing authentication and authorization in applications, ensuring secure access to resources and data. +17. **Testing and Debugging**: Next.js provides tools and utilities for testing and debugging applications, helping developers ensure the quality and reliability of their code. +18. **Continuous Integration and Deployment**: Next.js applications can be easily integrated with CI/CD pipelines for automated testing, building, and deployment processes. +19. **Serverless Functions**: Next.js allows developers to create serverless functions that can be deployed alongside their applications, enabling server-side logic without managing servers. +20. **Data Fetching Strategies**: Next.js supports various data fetching strategies, including `getStaticProps`, `getServerSideProps`, and `useSWR`, to fetch data at build time or on each request. +21. **Error Handling**: Next.js provides error handling mechanisms that help developers identify and resolve issues in their applications, ensuring a smooth user experience. +22. **Optimized Image Loading**: Next.js offers optimized image loading techniques, such as automatic image optimization and lazy loading, to improve performance and reduce bandwidth usage. +23. **SEO Metadata**: Next.js allows developers to define SEO metadata for pages, including titles, descriptions, and Open Graph tags, to enhance search engine visibility and social sharing. +24. **Accessibility**: Next.js promotes accessibility best practices by providing tools and guidelines for creating inclusive web applications that are usable by all users. +25. **Documentation and Support**: Next.js has comprehensive documentation and community support, making it easy for developers to learn and troubleshoot issues while building applications. + +By learning Next.js, developers can leverage these features and benefits to create high-performance, scalable, and modern web applications that meet the demands of today's digital landscape. + +## Conclusion + +Next.js is a powerful React framework that offers server-side rendering, static site generation, and a range of features to enhance the development process and application performance. By learning Next.js, developers can build fast, scalable, and SEO-friendly web applications with a seamless developer experience. Whether you are new to web development or looking to enhance your existing skills, Next.js provides a valuable toolkit for creating modern web applications that deliver exceptional user experiences.