Next.js url structure for multi language sites - next.js

I'm migrating my app to Next.js. Currently I have a url structure like this:
www.example.com/ <-- English
www.example.com/de <-- German
www.example.com/page <-- English
www.example.com/de/page <-- German
So my english website does not have the language in the url. If someone tries to access the website with "en" in the url he will be forwarded.
How would I achieve this in Next.js? Having always two files (i.e. "[language].js" and "index.js") in the /pages directory seems to be not the right solution.

As of Next.js 9.4 there is an experimental feature "Custom Routes". This provides a more elegent solution. See the discussion here: https://github.com/zeit/next.js/issues/9081
Example usage:
// next.config.js
module.exports = {
async rewrites() {
return [
// Basic `path-to-regexp` usage
// Query object shape: { id: string }
{ source: "/user/:id", destination: "/user_profile" },
// Optional Language
// Query object shape: { lang?: string }
{ source: "/:lang(en|es)?/about", destination: "/about" },
// Advanced rewrite
// Query object shape: { id: string } (in addition to dynamic route param)
{ source: "/u/:id", destination: "/user/:id" }
];
}
};

With NextJS 10 you can do this natively.
Your next.config.js would look like this:
module.exports = {
i18n: {
locales: ['en', 'de'],
defaultLocale: 'en',
},
}
The defaultLocale is the language for www.example.com/.
Then you can use a library like next-i18next to store the translations.

UPDATE: As nunorbatista said: With NextJS 10 you can do this natively. Your next.config.js would look like this:
module.exports = {
i18n: {
locales: ['en', 'de'],
defaultLocale: 'en',
},
}
Old answer:
The folder structure is correct, but you don’t need to write duplicate code inside [language] folder. Just import the page from ”main” folder. Multilingual is currenly a bit complex to setup with Next.js. Here is the situation at the moment.
If you want to use library
with serverless deployment you should watch this one.
https://github.com/vinissimus/next-translate
without serverless deployment you should watch this one.
https://github.com/isaachinman/next-i18next
If you want to do it on your own, you should modify them to match your needs.
Next.js version 9.3 or above
https://codesandbox.io/s/92ebn
Next.js version below 9.3
https://github.com/fwojciec/simple-i18n-example

Related

nuxt3 and vuetify3 Slow page response

I have created a front development environment using docker compose.
The configuration is nginx + nuxt3 + vuetify3.
I created vue in the Pages directory.
It took 120000ms to display it.
It's so slow that I can't even develop.
I'm trying to see why it's taking so long.
and it looks like it is getting all the vuetify code.
Also some of the requests are giving errors.
http://host.docker.internal/_nuxt/node_modules/vuetify/lib/components/VChip/VChip.css
http://host.docker.internal/_nuxt/node_modules/vuetify/lib/components/VGrid/VGrid.css
http://host.docker.internal/_nuxt/node_modules/nuxt/dist/pages/runtime/app.vue
http://host.docker.internal/_nuxt/node_modules/vuetify/lib/components/VNoSsr/VNoSsr.mjs?v=afbc0ebb
http://host.docker.internal/_nuxt/node_modules/vuetify/lib/components/VColorPicker/util/index.mjs?v=afbc0ebb
http://host.docker.internal/_nuxt/node_modules/vuetify/lib/components/VList/VListChildren.mjs?v=afbc0ebb
http://host.docker.internal/_nuxt/node_modules/vuetify/lib/components/VProgressCircular/VProgressCircular.css?v=afbc0ebb
The access is from host.docker.internal:80 leading to host machine:80 -> nginx container:80 -> nuxt container:3000.
The nuxt server is run by this command.
npx nuxi dev
I don't know why the above massive requests are taking place.
It also does not appear to be normal. What is wrong?
I am new to both nuxt and vuetify.
I am also not familiar with how webpack works.
Having the same issue, maybe it would be wise to add your nuxt config.
Maybe someone can figure out what to do..
Mine is as followed:
{
...
css: ['vuetify/styles'],
build: {
transpile: ['vuetify'],
},
modules: [
// eslint-disable-next-line require-await
async (_options, nuxt) => {
// #ts-ignore
nuxt.hooks.hook('vite:extendConfig', (config) => config?.plugins && config.plugins.push(vuetify({ autoImport: true })))
},
],
...
And plugins/vuetify.ts
// #ts-ignore
import {defineNuxtPlugin, useRuntimeConfig} from '#app'
import {createVuetify} from 'vuetify'
import * as components from 'vuetify/components'
import {aliases, mdi} from 'vuetify/iconsets/mdi-svg'
import { md3 } from 'vuetify/blueprints'
import {useDark} from '#vueuse/core'
export default defineNuxtPlugin((nuxtApp) => {
const isDark = useDark().value
const vuetify = createVuetify({
ssr: true,
// https://next.vuetifyjs.com/en/features/blueprints/
blueprint: md3,
components,
icons: {
defaultSet: 'mdi',
aliases,
sets: {
mdi,
},
},
// https://next.vuetifyjs.com/en/features/theme/
theme: {
defaultTheme: isDark ? 'dark' : 'light',
themes: {
dark, // theme defined earlier
light, // theme defined earlier
},
},
})
nuxtApp.vueApp.use(vuetify)
})

`next-sitemap` duplicated language in alternate ref path (href)

..I have a Next.js application with multi-language support (English as the default language and German as the secondary one - English is on https://mywebsite.com and German on https://mywebsite.com/de).
I'm using next-sitemap to generate a sitemap for the page using alternate refs to link the English and German versions of the pages. The following is my next-sitemap config:
/** #type {import('next-sitemap').IConfig} */
module.exports = {
siteUrl: `https://mywebsite.com`,
generateRobotsTxt: true,
exclude: ['/app/*', '/social-redirect'],
robotsTxtOptions: {
policies: [
{
userAgent: '*',
[process.env.VERCEL_ENV !== 'preview' && process.env.VERCEL_ENV !== 'development'
? 'allow'
: 'disallow']: '/',
},
],
},
alternateRefs: [
{
href: 'https://mywebsite.com',
hreflang: 'en',
},
{
href: 'https://mywebsite.com/de',
hreflang: 'de',
},
],
};
In the generated sitemap the English entries of the sitemap look good. They have the correct alternate refs. But in the German entries of the sitemap, the alternate refs have the language in the path twice, so for example: https://mywebsite.com/de/de/blog. Is this an issue of next-sitemap or am I doing something wrong? I would be glad if someone could help me with that!
This is also happening to me. I think it is an issue of next-sitemap
In my case I have languages en and en-gb The urls generated are:
<xhtml:link rel="alternate" hreflang="en" href="http://localhost:3000/en/en-gb/blog/"/>
<xhtml:link rel="alternate" hreflang="en-gb" href="http://localhost:3000/en-gb/en-gb/blog/"/>
You can use transform prop of next-sitemap.config.js to configure a replacement
`transform: async (config, path) => {
return { ...config,
loc: path.replace('/en-gb/en-gb', '/en-gb')
}
}

Linaria + Next.js + Path Aliases

I wanted to give Linaria (utilizing next-linaria) a try, but I'm currently stuck to get it working in any of my Next.js projects (that also use Typescript by the way).
The root of evil seems to be path aliases that are supported by Next.js by default.
tsconfig.json
...
"compilerOptions": {
...
"paths": {
"~/*": [
"src/*"
]
}
},
When just installing Linaria and next-linaria, I get an error like this:
Error: Can't resolve '~/layout/main/MainWrapper' in '[...]\src\layout\main'
I already know that Linaria stated to not support any other module aliasing than #babel-plugin-module-resolver or webpack. However, I can't get either of those to work.
I tried #babel-plugin-module-resolver and put same path configuration (and some other tries) to .babelrc without success.
"plugins": [
["module-resolver", {
"alias": {
"~/*": [
"src/*"
]
}
}]
]
I also tried doing the same with webpack aliases.
next.config.js
module.exports = withLinaria({
webpack: (config, { dev }) => {
config.resolve.alias = {
...config.resolve.alias,
"~/": path.resolve(__dirname, "./src/"),
};
return config;
},
});
The default project structure of Next.js looks like this:
/
/pages (contains entry points for each route)
/src (contains regular react components)
So, I'm kindly asking if anyone can tell us how to use path aliasing with Next + Linaria.

React CSS Module Import global CSS Library?

import '../../../../node_modules/react-responsive-carousel/lib/styles/carousel.min.css';
I have imported the above in my react app, but the classes are getting hashed since i am using css modules.. How can i import that css library in my component?
'use strict';
const autoprefixer = require('autoprefixer');
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin');
const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
const WatchMissingNodeModulesPlugin = require('react-dev-utils/WatchMissingNodeModulesPlugin');
const eslintFormatter = require('react-dev-utils/eslintFormatter');
const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin');
const getClientEnvironment = require('./env');
const paths = require('./paths');
// Webpack uses `publicPath` to determine where the app is being served from.
// In development, we always serve from the root. This makes config easier.
const publicPath = '/';
// `publicUrl` is just like `publicPath`, but we will provide it to our app
// as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript.
// Omit trailing slash as %PUBLIC_PATH%/xyz looks better than %PUBLIC_PATH%xyz.
const publicUrl = '';
// Get environment variables to inject into our app.
const env = getClientEnvironment(publicUrl);
// This is the development configuration.
// It is focused on developer experience and fast rebuilds.
// The production configuration is different and lives in a separate file.
module.exports = {
// You may want 'eval' instead if you prefer to see the compiled output in DevTools.
// See the discussion in https://github.com/facebookincubator/create-react-app/issues/343.
devtool: 'cheap-module-source-map',
// These are the "entry points" to our application.
// This means they will be the "root" imports that are included in JS bundle.
// The first two entry points enable "hot" CSS and auto-refreshes for JS.
entry: [
// We ship a few polyfills by default:
require.resolve('./polyfills'),
// Include an alternative client for WebpackDevServer. A client's job is to
// connect to WebpackDevServer by a socket and get notified about changes.
// When you save a file, the client will either apply hot updates (in case
// of CSS changes), or refresh the page (in case of JS changes). When you
// make a syntax error, this client will display a syntax error overlay.
// Note: instead of the default WebpackDevServer client, we use a custom one
// to bring better experience for Create React App users. You can replace
// the line below with these two lines if you prefer the stock client:
// require.resolve('webpack-dev-server/client') + '?/',
// require.resolve('webpack/hot/dev-server'),
require.resolve('react-dev-utils/webpackHotDevClient'),
// Finally, this is your app's code:
paths.appIndexJs,
// We include the app code last so that if there is a runtime error during
// initialization, it doesn't blow up the WebpackDevServer client, and
// changing JS code would still trigger a refresh.
],
output: {
// Add /* filename */ comments to generated require()s in the output.
pathinfo: true,
// This does not produce a real file. It's just the virtual path that is
// served by WebpackDevServer in development. This is the JS bundle
// containing code from all our entry points, and the Webpack runtime.
filename: 'static/js/bundle.js',
// There are also additional JS chunk files if you use code splitting.
chunkFilename: 'static/js/[name].chunk.js',
// This is the URL that app is served from. We use "/" in development.
publicPath: publicPath,
// Point sourcemap entries to original disk location (format as URL on Windows)
devtoolModuleFilenameTemplate: info =>
path.resolve(info.absoluteResourcePath).replace(/\\/g, '/'),
},
resolve: {
// This allows you to set a fallback for where Webpack should look for modules.
// We placed these paths second because we want `node_modules` to "win"
// if there are any conflicts. This matches Node resolution mechanism.
// https://github.com/facebookincubator/create-react-app/issues/253
modules: ['node_modules', paths.appNodeModules].concat(
// It is guaranteed to exist because we tweak it in `env.js`
process.env.NODE_PATH.split(path.delimiter).filter(Boolean)
),
// These are the reasonable defaults supported by the Node ecosystem.
// We also include JSX as a common component filename extension to support
// some tools, although we do not recommend using it, see:
// https://github.com/facebookincubator/create-react-app/issues/290
// `web` extension prefixes have been added for better support
// for React Native Web.
extensions: ['.web.js', '.mjs', '.js', '.json', '.web.jsx', '.jsx'],
alias: {
// Support React Native Web
// https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
'react-native': 'react-native-web',
},
plugins: [
// Prevents users from importing files from outside of src/ (or node_modules/).
// This often causes confusion because we only process files within src/ with babel.
// To fix this, we prevent you from importing files out of src/ -- if you'd like to,
// please link the files into your node_modules/ and let module-resolution kick in.
// Make sure your source files are compiled, as they will not be processed in any way.
new ModuleScopePlugin(paths.appSrc, [paths.appPackageJson]),
],
},
module: {
strictExportPresence: true,
rules: [
// TODO: Disable require.ensure as it's not a standard language feature.
// We are waiting for https://github.com/facebookincubator/create-react-app/issues/2176.
// { parser: { requireEnsure: false } },
// First, run the linter.
// It's important to do this before Babel processes the JS.
{
test: /\.(js|jsx|mjs)$/,
enforce: 'pre',
use: [
{
options: {
formatter: eslintFormatter,
eslintPath: require.resolve('eslint'),
},
loader: require.resolve('eslint-loader'),
},
],
include: paths.appSrc,
},
{
// "oneOf" will traverse all following loaders until one will
// match the requirements. When no loader matches it will fall
// back to the "file" loader at the end of the loader list.
oneOf: [
// "url" loader works like "file" loader except that it embeds assets
// smaller than specified limit in bytes as data URLs to avoid requests.
// A missing `test` is equivalent to a match.
{
test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
loader: require.resolve('url-loader'),
options: {
limit: 10000,
name: 'static/media/[name].[hash:8].[ext]',
},
},
// Process JS with Babel.
{
test: /\.(js|jsx|mjs)$/,
include: paths.appSrc,
loader: require.resolve('babel-loader'),
options: {
// This is a feature of `babel-loader` for webpack (not Babel itself).
// It enables caching results in ./node_modules/.cache/babel-loader/
// directory for faster rebuilds.
cacheDirectory: true,
},
},
// "postcss" loader applies autoprefixer to our CSS.
// "css" loader resolves paths in CSS and adds assets as dependencies.
// "style" loader turns CSS into JS modules that inject <style> tags.
// In production, we use a plugin to extract that CSS to a file, but
// in development "style" loader enables hot editing of CSS.
{
test: /\.css$/,
use: [
require.resolve('style-loader'),
{
loader: require.resolve('css-loader'),
options: {
importLoaders: 1,
modules: true,
localIdentName: '[name]_[local]_[hash:base64:5]'
},
},
{
loader: require.resolve('postcss-loader'),
options: {
// Necessary for external CSS imports to work
// https://github.com/facebookincubator/create-react-app/issues/2677
ident: 'postcss',
plugins: () => [
require('postcss-flexbugs-fixes'),
autoprefixer({
browsers: [
'>1%',
'last 4 versions',
'Firefox ESR',
'not ie < 9', // React doesn't support IE8 anyway
],
flexbox: 'no-2009',
}),
],
},
},
],
},
// "file" loader makes sure those assets get served by WebpackDevServer.
// When you `import` an asset, you get its (virtual) filename.
// In production, they would get copied to the `build` folder.
// This loader doesn't use a "test" so it will catch all modules
// that fall through the other loaders.
{
// Exclude `js` files to keep "css" loader working as it injects
// its runtime that would otherwise processed through "file" loader.
// Also exclude `html` and `json` extensions so they get processed
// by webpacks internal loaders.
exclude: [/\.(js|jsx|mjs)$/, /\.html$/, /\.json$/],
loader: require.resolve('file-loader'),
options: {
name: 'static/media/[name].[hash:8].[ext]',
},
},
],
},
// ** STOP ** Are you adding a new loader?
// Make sure to add the new loader(s) before the "file" loader.
],
},
plugins: [
// Makes some environment variables available in index.html.
// The public URL is available as %PUBLIC_URL% in index.html, e.g.:
// <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
// In development, this will be an empty string.
new InterpolateHtmlPlugin(env.raw),
// Generates an `index.html` file with the <script> injected.
new HtmlWebpackPlugin({
inject: true,
template: paths.appHtml,
}),
// Add module names to factory functions so they appear in browser profiler.
new webpack.NamedModulesPlugin(),
// Makes some environment variables available to the JS code, for example:
// if (process.env.NODE_ENV === 'development') { ... }. See `./env.js`.
new webpack.DefinePlugin(env.stringified),
// This is necessary to emit hot updates (currently CSS only):
new webpack.HotModuleReplacementPlugin(),
// Watcher doesn't work well if you mistype casing in a path so we use
// a plugin that prints an error when you attempt to do this.
// See https://github.com/facebookincubator/create-react-app/issues/240
new CaseSensitivePathsPlugin(),
// If you require a missing module and then `npm install` it, you still have
// to restart the development server for Webpack to discover it. This plugin
// makes the discovery automatic so you don't have to restart.
// See https://github.com/facebookincubator/create-react-app/issues/186
new WatchMissingNodeModulesPlugin(paths.appNodeModules),
// Moment.js is an extremely popular library that bundles large locale files
// by default due to how Webpack interprets its code. This is a practical
// solution that requires the user to opt into importing specific locales.
// https://github.com/jmblog/how-to-optimize-momentjs-with-webpack
// You can remove this if you don't use Moment.js:
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
],
// Some libraries import Node modules but don't use them in the browser.
// Tell Webpack to provide empty mocks for them so importing them works.
node: {
dgram: 'empty',
fs: 'empty',
net: 'empty',
tls: 'empty',
child_process: 'empty',
},
// Turn off performance hints during development because we don't do any
// splitting or minification in interest of speed. These warnings become
// cumbersome.
performance: {
hints: false,
},
};
This is my webpack config file. I tried looking around and some people seem use ~ which doesnt work on my app, seems like my app doesnt know what ~ is. Some people seem to use import !style-loader!css-loader etc... but it doesnt work in my app as well.. it looks like my app doesnt know what to do with the !. It will not compile. I have been searching for days and i can't seem to figure it out.
btw i'm new to this webpack react stuff, if you answer something please try to include as much detail as possible so i can understand it. thank you!
I started my app with create-react-app and then did eject on the app to get access to the config files..

White label sass/css with Webpack

I'm trying generate multiple css files with webpack for a white labeled application.
I want to run the webpack css/sass loaders one time for each 'brand' and output it in to a separate file. I want to do this as I have a separate variable file for each brand and would want the sass to compile one css file for each brand.
I think I can do this with grunt/gulp, but I wanted to avoid including them in this project.
I've been working on this exact problem lately. I found the i18n example config to be illustrative of how it's possible to do this. Basically the webpack config can be an array. You could do something like this.
import webpack from 'webpack';
export default [
{
entry: {
'brand-1': ['path/to/vars-1.scss', 'path/to/my.scss'],
}
// ...
},
{
entry: {
'brand-2': ['path/to/vars-2.scss', 'path/to/my.scss'],
}
// ...
},
];
Obviously you could generate the list, but I wrote it out for clarity. Our SCSS variables are dynamic, so I wrote a script that creates the webpack config and then injects the variables using the sassLoader.data option.
You may also want to use webpack-merge in order to separate the configs.
const common = {
module: {
loaders: {
// ...
},
},
};
export default BRANDS.map((brand) => (
merge(
common,
{
entry: {
[brand.name]: [brand.variableFile, 'path/to/my.scss'],
},
// If you needed something like this.
plugins: [
webpack.DefinePlugin({
BRAND_NAME: brand.name,
}),
],
},
)
));
I'm using the ExtractTextPlugin, and I instantiate one for each brand. I'm not sure if that's the correct thing to do.
I also have not figured out how this interacts with the CommonChunksPlugin, but I hope I can work something out.

Resources