How to start building an internationalized Next.js project
Tags: react, tutorial, beginners, typescript
Published: 2023-09-02 08:04:53



[Online Preview](https://nglobe.vercel.app/)

All code from this tutorial as a complete package is available in [this repository](https://github.com/reeswell/nglobe).

If you found this tutorial helpful, please star it and share it with your friends and colleagues!

## 1、Set Up Multiple Languages

![Kapture 2023-09-01 at 02.04.52](https://cdn.jsdelivr.net/gh/xxydrr/my_pic/img/Kapture%202023-09-01%20at%2002.04.52.gif)

To achieve multiple language support, we will use the `next-intl` plugin provided by Next.js. This plugin offers a simple and flexible way to handle internationalization. We will install and configure `next-intl` and create language files to store translations for different languages.
`middleware.ts`

```ts
import { withAuth } from 'next-auth/middleware'
import createIntlMiddleware from 'next-intl/middleware'
import type { NextRequest } from 'next/server'

const locales = ['en', 'de', 'zh']
const publicPages = ['/', '/sign-in', '/sign-up', '/about']

const intlMiddleware = createIntlMiddleware({
  locales,
  defaultLocale: 'en',
})

const authMiddleware = withAuth(
  // Note that this callback is only invoked if
  // the `authorized` callback has returned `true`
  // and not for pages listed in `pages`.
  function onSuccess(req) {
    return intlMiddleware(req)
  },
  {
    callbacks: {
      authorized: ({ token }) => token != null,
    },
    pages: {
      signIn: '/sign-in',
    },
  }
)

export default function middleware(req: NextRequest) {
  const publicPathnameRegex = RegExp(
    `^(/(${locales.join('|')}))?(${publicPages.join('|')})?/?$`,
    'i'
  )
  const isPublicPage = publicPathnameRegex.test(req.nextUrl.pathname)

  if (isPublicPage) {
    return intlMiddleware(req)
  } else {
    // eslint-disable-next-line
    return (authMiddleware as any)(req)
  }
}

export const config = {
  // Skip all paths that should not be internationalized. This example skips the
  // folders "api", "_next" and all files with an extension (e.g. favicon.ico)
  matcher: ['/((?!api|_next|.*\\..*).*)'],
}

```

## 2、Implement Theme Switching

![Kapture 2023-09-01 at 02.14.09](https://cdn.jsdelivr.net/gh/xxydrr/my_pic/img/Kapture%202023-09-01%20at%2002.14.09.gif)

To enable theme switching functionality, we will utilize the `useTheme` hook from `next-themes`.

`ThemeSwitch.tsx`

```tsx
interface ThemeSwitchProps
  extends React.ButtonHTMLAttributes<HTMLButtonElement> {}

const ThemeSwitch: FC<ThemeSwitchProps> = ({ className }) => {
  const { systemTheme, theme, setTheme } = useTheme()
  const currentTheme = theme === 'system' ? systemTheme : theme

  return (
    <button
      className={className}
      onClick={() => setTheme(currentTheme === 'light' ? 'dark' : 'light')}
    >
      {currentTheme === 'light' ? <BsFillMoonStarsFill /> : <BsFillSunFill />}
    </button>
  )
}
```

## 3、Design Responsive Layouts

![Kapture 2023-09-01 at 02.52.58](https://cdn.jsdelivr.net/gh/xxydrr/my_pic/img/Kapture%202023-09-01%20at%2002.52.58.gif)

To ensure our application displays well on different devices, we will use Tailwind CSS to implement responsive design. Tailwind CSS provides a powerful set of tools and utility classes for simplifying responsive layout development.

## 4、Authentication

![image-20230901234403726](https://cdn.jsdelivr.net/gh/xxydrr/my_pic/img/image-20230901234403726.png)

To implement authentication functionality, we will use NextAuth.js. NextAuth.js is a simple and flexible authentication library that supports various identity providers, including Google and GitHub providers.

## 5、Build UI Components with Shadcn UI

Shadcn UI is a powerful and user-friendly UI component library that offers a range of pre-built components to help us quickly create beautiful and consistent user interfacesWe need to define an `components.json` file.

`components.json`

```json
{
  "$schema": "https://ui.shadcn.com/schema.json",
  "style": "new-york",
  "rsc": true,
  "tailwind": {
    "config": "tailwind.config.js",
    "css": "./src/styles/globals.css",
    "baseColor": "slate",
    "cssVariables": true
  },
  "aliases": {
    "components": "@/components",
    "utils": "@/lib/utils"
  }
}
```

We need to add a button component just run

```shell
npx shadcn-ui@latest add button
```

## 6、Validate Data with Zod

To ensure data validity and security, we will use Zod for data validation. Zod is a powerful data validation library that provides a simple and flexible API for defining and validating data structures.

For example, simple verification of account passwords

> lib>validations>auth.ts

```ts
import * as z from 'zod'

export const authValidator = z.object({
  email: z.string().email({
    message: 'Please enter a valid email address',
  }),
  password: z.string().min(6, {
    message: 'Password must be at least 8 characters long',
  }),
})

```

## 7、Code Formatting and Quality Tools

In order to set a standard that will be used by all contributors to the project to keep the code style consistent and basic best practices followed we will be implementing the following tools:

- [eslint](https://eslint.org/) - For best practices on coding standards
- [prettier](https://prettier.io/) - For automatic formatting of code files
- `eslint-plugin-tailwindcss` - Best Practices for Tailwind CSS Coding Standards
- `prettier-plugin-tailwindcss`- For automatic formatting of Tailwind CSS files

## Summary

In this blog, we learned how to build a Next.js project and implemented the following features:

**1、Set up multiple languages:** We used the next-intl plugin provided by Next.js to achieve multiple language support. We installed and configured next-intl and created language files to store translations for different languages.

**2、Implement theme switching:** We utilized the useTheme hook from next-themes to enable theme switching functionality.

**3、Design responsive layouts:** We used Tailwind CSS to implement responsive design and ensure our application displays well on different devices.

**4、Authentication:** We implemented authentication functionality using NextAuth.js, a simple and flexible authentication library that supports various identity providers.

**5、Build UI components with Shadcn UI:** We utilized Shadcn UI, a powerful and user-friendly UI component library, to create beautiful and consistent user interfaces.

**6、Validate data with Zod:** We used Zod, a data validation library, to ensure data validity and security in our application.

**7、Code formatting and quality tools:** We implemented ESLint and Prettier to enforce coding standards, automatic code formatting, and best practices.

By following these steps, we created a Next.js project with features such as multiple language support, theme switching, responsive layouts, authentication, UI components, data validation, and code quality assurance.

If you found this tutorial helpful, please star it and share it with your friends and colleagues!
[this repository](https://github.com/reeswell/nglobe)