adding export script to an existing next.config.js - next.js

I'm following Microsoft's Tutorial:
Deploy static-rendered Next.js websites on Azure Static Web Apps
The problem is, I'm trying to add to my next.config.js file this code:
const data = require('./utils/projectsData');
module.exports = {
trailingSlash: true,
exportPathMap: async function () {
const { projects } = data;
const paths = {
'/': { page: '/' },
};
projects.forEach((project) => {
paths[`/project/${project.slug}`] = {
page: '/project/[path]',
query: { path: project.slug },
};
});
return paths;
},
};
but my next.config.js already has some existing content:
require('dotenv').config()
const withFonts = require('next-fonts')
module.exports = withFonts({
serverRuntimeConfig: {},
trailingSlash: true,
exportPathMap: function() {
return {
'/': { page: '/' }
};
},
publicRuntimeConfig: {
API_URL: process.env.API_URL,
PORT: process.env.PORT || 3000,
PUBLISHABLE_KEY: process.env.PUBLISHABLE_KEY,
},
})
how can I combine them?

Just combine them like that?
require('dotenv').config()
const data = require('./utils/projectsData'); // Add this line
const withFonts = require('next-fonts')
module.exports = withFonts({
serverRuntimeConfig: {},
trailingSlash: true,
// And override this key
exportPathMap: async function () {
const { projects } = data;
const paths = {
'/': { page: '/' },
};
projects.forEach((project) => {
paths[`/project/${project.slug}`] = {
page: '/project/[path]',
query: { path: project.slug },
};
});
return paths;
},
publicRuntimeConfig: {
API_URL: process.env.API_URL,
PORT: process.env.PORT || 3000,
PUBLISHABLE_KEY: process.env.PUBLISHABLE_KEY,
},
})

Related

Error when use remote components with hooks and module federations with nextjs

I receive this error when use hooks in component from remote app when
enter image description here
i use now nextjs13 with module federations
how to resolve this
enter code here
my component remote app
'use client'
import { useState } from 'react'
export default function Button() {
const [count, setCount] = useState(0)
return (
<div>
<button onClick={() => setCount(count + 1)}>adicionar</button>
<h1>{count}</h1>
</div>
)
}
my component in host
'use client'
import dynamic from 'next/dynamic'
import React, { useState } from 'react'
const RemoteComponent = dynamic({
loader: async () => {
const { default: RemoteComponent } = await import('front_login/Button')
return () => <RemoteComponent />
},
})
export default function Auth() {
return (
<>
<RemoteComponent />
</>
)
}
my next-config.js in host
const { NextFederationPlugin } = require('#module-federation/nextjs-mf')
/** #type {import('next').NextConfig} */
const nextConfig = {
output: 'standalone',
experimental: {
appDir: true,
},
webpack: (config, options) => {
const { isServer } = options
Object.assign(config.experiments, { topLevelAwait: true })
config.watchOptions = {
poll: 1000,
aggregateTimeout: 300,
}
config.plugins.push(
new NextFederationPlugin({
name: 'front_gateway',
remotes: {
front_login: `front_login#${process.env.FRONT_LOGIN}/_next/static/${
isServer ? 'ssr' : 'chunks'
}/remoteEntry.js`,
},
filename: 'static/chunks/remoteEntry.js',
shared: {
'styled-components': {
requiredVersion: false,
eager: true,
singleton: true,
},
},
}),
)
return config
},
}
module.exports = nextConfig
my next config in remote app
/** #type {import('next').NextConfig} */
const { NextFederationPlugin } = require('#module-federation/nextjs-mf')
const nextConfig = {
output: 'standalone',
experimental: {
appDir: true,
},
webpack: (config, options) => {
const { isServer } = options
config.watchOptions = {
poll: 1000,
aggregateTimeout: 300,
}
config.plugins.push(
new NextFederationPlugin({
name: 'front_login',
remotes: {
front_gateway: `front_gateway#${
process.env.FRONT_GATEWAY
}/_next/static/${isServer ? 'ssr' : 'chunks'}/remoteEntry.js`,
},
filename: 'static/chunks/remoteEntry.js',
exposes: {
'./Button': './src/app/components/Button/button.tsx',
'./Doidao': './src/app/doidao/page.tsx',
},
shared: {
'styled-components': {
singleton: true,
eager: true,
requiredVersion: false,
},
},
}),
)
return config
},
}
module.exports = nextConfig
Please i need help to fix this
When use remote component in remote app, work with success but in host not working

Redirect function in Nuxt middleware is making state null

I have a Nuxt app in which everything works fine in middleware except when I use redirect.
When I comment the redirect('/admin') line it works fine even the state data is present when console logged. As soon as I uncomment the redirect line it makes the state null.
Please help if someone knows this issue. This exact code works in my other projects but not here.
This is my auth.js file in the middleware folder.
export default function ({ store, route, redirect }) {
const user = store.getters['user/user']
const blockRouteAdmin = /\/admin\/*/g
const blockRouteManager = /\/manager\/*/g
const path = ['/signup', '/login']
let value = path.includes(route.path)
if (user) {
if (user.isAdmin) {
if (!route.path.match(blockRouteAdmin)) {
redirect('/admin')
}
}
if (user.isManager) {
if (!route.path.match(blockRouteManager)) {
redirect('/manager')
}
}
if (user.isUser) {
if (
route.path.match(blockRouteAdmin) ||
route.path.match(blockRouteManager) ||
value
) {
console.log('isUser', user.isUser)
redirect('/')
}
}
}
if (!user) {
if (
route.path.match(blockRouteAdmin) ||
route.path.match(blockRouteManager)
) {
redirect('/')
} else {
redirect()
}
}
}
Here is my nuxt.config.js
export default {
// Target: https://go.nuxtjs.dev/config-target
target: 'static',
// Global page headers: https://go.nuxtjs.dev/config-head
head: {
title: 'aitl',
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{ hid: 'description', name: 'description', content: '' },
{ name: 'format-detection', content: 'telephone=no' },
],
link: [{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }],
},
// Global CSS: https://go.nuxtjs.dev/config-css
css: [],
// Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins
plugins: ['~/plugins/firebaseConfig.js'],
// Auto import components: https://go.nuxtjs.dev/config-components
components: true,
// Modules for dev and build (recommended): https://go.nuxtjs.dev/config-modules
buildModules: [],
// Modules: https://go.nuxtjs.dev/config-modules
modules: [
// https://go.nuxtjs.dev/buefy
'nuxt-buefy',
// https://go.nuxtjs.dev/pwa
'#nuxtjs/pwa',
// https://go.nuxtjs.dev/content
'#nuxt/content',
],
// PWA module configuration: https://go.nuxtjs.dev/pwa
pwa: {
manifest: {
lang: 'en',
},
},
// Content module configuration: https://go.nuxtjs.dev/config-content
content: {},
// Build Configuration: https://go.nuxtjs.dev/config-build
build: {},
}
My index.js inside store.
import { vuexfireMutations } from 'vuexfire'
import { getUserFromCookie } from '../helper/index.js'
export const mutations = {
...vuexfireMutations,
}
export const actions = {
async nuxtServerInit({ dispatch, commit }, { req }) {
try {
const user = getUserFromCookie(req)
if (user) {
await dispatch('user/setUSER', {
email: user.email,
isAdmin: user.admin,
isManager: user.manager,
isUser: user.user,
uid: user.user_id,
name: user.name,
})
}
} catch (err) {
console.log(err)
}
},
}
User.js in store folder
import { auth } from '../plugins/firebaseConfig'
import Cookies from 'js-cookie'
export const state = () => ({
user: null,
})
export const getters = {
user(state) {
return state.user
},
}
export const actions = {
async userlogin({ dispatch }, user) {
try {
const token = await auth.currentUser.getIdToken(true)
const userInfo = {
email: user.email,
isAdmin: user.admin,
isManager: user.manager,
isUser: user.user,
uid: user.uid,
name: user.displayName,
}
Cookies.set('access_token', token)
await dispatch('setUSER', userInfo)
} catch (err) {
console.log(err)
}
},
setUSER({ commit }, user) {
commit('setUSER', user)
},
}
export const mutations = {
setUSER(state, user) {
state.user = user
},
}
The issue was solved by going from target: 'static' to target: 'server', aka mirroring the settings of another working project.

NextJS: New nonce on every application load while enabling CSP

I am trying to implement strict-dynamic CSP rules for my nextjs application. I want a new nonce value at every app load, but it is not happening. Currently a value is set for every build. Since I need the nonce value to set headers for the web pages, I need it in next.config.js.
Please let me know what I'm doing wrong.
next.config.js
const { v4 } = require('uuid');
const { createSecureHeaders } = require("next-secure-headers");
const crypto = require('crypto');
const { PHASE_DEVELOPMENT_SERVER } = require("next/constants");
const generatedNonce = function nonceGenerator() {
const hash = crypto.createHash('sha256');
hash.update(v4());
return hash.digest('base64');
}();
module.exports = function nextConfig(phase, { defaultConfig }) {
return {
publicRuntimeConfig: {
generatedNonce
},
headers: async () => {
return [
{
source: "/(.*)?",
headers: createSecureHeaders({
contentSecurityPolicy: {
directives: {
defaultSrc: ["'none"],
scriptSrc: [
...(phase === PHASE_DEVELOPMENT_SERVER ? ["'unsafe-eval'"] : []),
`'nonce-${generatedNonce}'`,
"'strict-dynamic'",
],
},
},
nosniff: "nosniff",
referrerPolicy: "no-referrer",
frameGuard: "sameorigin",
})
}
]
}
};
}

NextJS Build error: package.json does not exist at /package.json

I have been working on a NextJS application that utilizes Firebase. I have everything set up and on build I get the following error: package.json does not exist at /package.json (see the image)
build error
To give more context on this:
NextJS v^9.3.0
Firebase v^7.10.0
Target: server (by default)
My next.config.js:
const path = require('path')
const resolve = require('resolve')
const withCSS = require('#zeit/next-css')
const withImages = require('next-images')
const withFonts = require('next-fonts')
const withTM = require('next-transpile-modules')([
'*************',
'*************',
'*************'
]);
if (typeof require !== "undefined") {
require.extensions[".less"] = () => {};
require.extensions[".css"] = (file) => {};
}
module.exports =
withCSS(
withImages(
withFonts(
withTM({
webpack: (config, options) => {
config.module.rules.push({
test: /\.svg$/,
use: ['#svgr/webpack'],
});
const { dir, isServer } = options
config.externals = []
if (isServer) {
config.externals.push((context, request, callback) => {
resolve(request, { basedir: dir, preserveSymlinks: true }, (err, res) => {
if (err) {
return callback()
}
if (
res.match(/node_modules[/\\].*\.css/)
&& !res.match(/node_modules[/\\]webpack/)
&& !res.match(/node_modules[/\\]#aws-amplify/)
) {
return callback(null, `commonjs ${request}`)
}
callback()
})
})
}
return config;
},
cssLoaderOptions: {
url: false
}
})
)
)
)
I have been trying many solutions, including the following:
- I should use target server, but I have also tried with "experimental-serverless-trace" but no effect, same error persists
- Tried also "webpack-asset-relocator-loader" but it doesn't work as well. When utilized, I get the following error: "gRPC binary module was not installed".
To be honest, at this point I do not have any idea where to go from this point.
Thanks!

Problem with nuxt (SSR) and firestore rules

I use Nuxt (universal mode) with Firestore, I set rules properly but I still get this error:
I get Missing or insufficient permissions
when I reload the page. When ccessing the page through the router, I don't get any error, the rules re working as it's supposed to.
Firestore is called in the asyncData (as it's a SSR app).
If I check the req.user in asynData when loading the page, everything looks fine. I have the roles and all information. It seems that serverMiddleware is activated after the asyncData, when reloading the browser. Any ideas why?
My Firestore rules:
service cloud.firestore {
match /databases/{database}/documents {
function isApplicant() {
return request.auth.token.roles.applicant == true
}
match /tests/{test} {
allow read: if isApplicant();
}
}
}
serverMiddleware:
const admin = require('../services/firebase-admin-init.js')
const cookieParser = require('cookie-parser')();
global.XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest
module.exports = async function (req, res, next) {
await getIdTokenFromRequest(req, res).then(idToken => {
if (idToken) {
addDecodedIdTokenToRequest(idToken, req).then(() => {
next();
});
} else {
next();
}
});
}
function getIdTokenFromRequest(req, res) {
if (req.headers.authorization && req.headers.authorization.startsWith('Bearer ')) {
return Promise.resolve(req.headers.authorization.split('Bearer ')[1]);
}
return new Promise(function(resolve) {
cookieParser(req, res, () => {
if (req.cookies && req.cookies.__session) {
console.log("new")
console.log('Found "__session" cookie');
// Read the ID Token from cookie.
resolve(req.cookies.__session);
} else {
resolve();
}
});
});
}
/**
* Returns a Promise with the Decoded ID Token and adds it to req.user.
*/
function addDecodedIdTokenToRequest(idToken, req) {
// console.log('Start addDecodedIdTokenToRequest')
return admin.auth().verifyIdToken(idToken).then(decodedIdToken => {
console.log('ID Token correctly decoded', decodedIdToken);
req.user = decodedIdToken;
}).catch(error => {
console.error('Error while verifying Firebase ID token:', error);
});
}
Nuxt config files:
const path = require('path');
const environment = process.env.NODE_ENV || 'development';
const envSet = require(`./config/env.${environment}.js`);
module.exports = {
env: envSet,
mode: 'universal',
plugins: [
{ src: '~/plugins/fireinit.js', ssr: false, },
{ src: '~/plugins/auth-cookie.js', ssr: false },
{ src: '~/plugins/fireauth.js', ssr: false }
],
router: {
},
serverMiddleware: [
'~/serverMiddleware/validateFirebaseIdToken'
],
modules: [
'vue-scrollto/nuxt',
['nuxt-validate', {
lang: 'ja'
}],
'#nuxtjs/axios',
],
css: [
{src: '~/assets/scss/app.scss', lang: 'scss'}
],
/*
** Customize the progress bar color
*/
loading: { color: '#403a8f' },
resolve: {
extensions: ['.js', '.json', '.vue', '.ts'],
root: path.resolve(__dirname),
alias: {
'~': path.resolve(__dirname),
'#': path.resolve(__dirname)
},
},
/*
** Build configuration
*/
buildDir: '../cloud/front/',
build: {
publicPath: '/assets/',
extractCSS: true,
quiet: false,
terser: {
terserOptions: {
compress: {
drop_console: environment === 'production' ? true : false,
},
},
},
},
}

Resources