Как добавить заголовки ответов в общедоступные ресурсы NextJS?

#express #http-headers #next.js #response-headers

#выражать #http-заголовки #next.js #ответ-заголовки

Вопрос:

Я хочу установить заголовок max-age ответа для моих изображений и шрифтов в NextJS.

Я нашел этот документ из NextJS, но поскольку я использую next-compose-plugins , не совсем понятно, как включить это в мой текущий код https://nextjs.org/docs/api-reference/next.config.js/headers

У меня настроен экспресс-сервер, поэтому при необходимости я мог бы использовать его, но опять же не совсем уверен, где и как установить там заголовки.

Мой текущий next.config.js (NextJS v9.5.5):

 const webpack = require('webpack');
const sass = require('@zeit/next-sass');
const CSS = require('@zeit/next-css');
const withPlugins = require('next-compose-plugins');
const fonts = require('next-fonts');
const progressBar = require('next-progressbar')

const OptimizeCSSAssetsPlugin = require("optimize-css-assets-webpack-plugin");

const nextConfig = {
  serverRuntimeConfig: { // Will only be available on the server side
    
  },
  publicRuntimeConfig: { // Will be available on both server and client
    DOMAIN: process.env.NODE_ENV == 'production' ? 'http://example.com' : 'https://example.local',
    SITENAME: process.env.NODE_ENV == 'production' ? 'Site Name' : 'Local Site Name'
  }
}

module.exports = withPlugins([
  [sass({
    webpack(config, options) {
      config.optimization.minimizer = [];
      config.optimization.minimizer.push(new OptimizeCSSAssetsPlugin({}));

    return config;
    }
  })],
  // sass,
  CSS,
  fonts,
  progressBar
  // your other plugins here
 
], 
nextConfig);
 

Server.js:

 const express = require( 'express' );
const next    = require( 'next' );
const bodyParser = require('body-parser');
const compression = require('compression');

// Import middleware.
const pageRoutes = require( './routes/pageRoutes' );

// Setup app.
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle  = app.getRequestHandler();
const handler = pageRoutes.getRequestHandler( app );

// setup server
app.prepare()
  .then( () => {
    // Create server.
    const server = express();

    // this is for forms
    server.use(bodyParser.urlencoded({ extended: true }));
    server.use(bodyParser.json());
    server.use(compression());
    const formRoutes = require( './routes' );
    formRoutes(server);

    // Use our handler for requests.
    server.use( handler );


    // Don't remove. Important for the server to work. Default route.
    server.get( '*', ( req, res ) => {
      res.setHeader("test", 25);
      return handle( req, res );
    } );

    // Get current port.
    const port = process.env.PORT || 8080;

    // Error check.
    server.listen( port, err => {
      if ( err ) {
        throw err;
      }

      // Where we starting, yo!
      console.log( `> Ready on port ${port}...` );
    } );
  } );
 

Ответ №1:

Внутри объявления nextConfig просто поместите

 async headers() {...},
 

итак, наконец, это стало бы

 const nextConfig = {
    async headers() {
        return [
           {
              source: '/:all*(svg|jpg|png)',
              locale: false,
              headers: [
              {
                 key: 'Cache-Control',
                 value: 'public, max-age=9999999999, must-revalidate',
              }
        ],
      },
        ],
      },
  serverRuntimeConfig: { // Will only be available on the server side
    
  },
  publicRuntimeConfig: { // Will be available on both server and client
    DOMAIN: process.env.NODE_ENV == 'production' ? 'http://example.com' : 'https://example.local',
    SITENAME: process.env.NODE_ENV == 'production' ? 'Site Name' : 'Local Site Name'
  }
}
 

Комментарии:

1. Спасибо, я попробую.